Jquery-traversal-map

提供:Dev Guides
移動先:案内検索

jQuery-map(コールバック)メソッド

説明

  • map(コールバック)*メソッドは、jQueryオブジェクト内の要素のセットを、要素を含む場合と含まない場合があるjQuery配列内の別の値のセットに変換します。

このメソッドを使用して、値、属性、CSS値のリストを作成したり、特別なカスタムセレクター変換を実行することもできます。

構文

このメソッドを使用するための簡単な構文は次のとおりです-

selector.map( callback )

パラメーター

これは、この方法で使用されるすべてのパラメータの説明です-

  • callback -セット内の各要素で実行する関数。

以下は、このメソッドの使用方法を示す簡単な例です-

<html>
   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript"
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
      </script>

      <script type = "text/javascript" language = "javascript">
         $(document).ready(function(){

            var mappedItems = $("li").map(function (index) {
               var replacement = $("<li>").text($(this).text()).get(0);

               if (index == 0) {
                 //make the first item all caps
                  $(replacement).text($(replacement).text().toUpperCase());
               } else if (index == 1 || index == 3) {
                 //delete the second and fourth items
                  replacement = null;
               } else if (index == 2) {
                 //make two of the third item and add some text
                  replacement = [replacement,$("<li>").get(0)];
                  $(replacement[0]).append("<b> - A</b>");
                  $(replacement[1]).append("Extra <b> - B</b>");
               }

              //replacement will be an dom element, null,
              //or an array of dom elements
               return replacement;
            });

            $("#results").append(mappedItems);
         });
      </script>

      <style>
         body { font-size:16px; }
         ul { float:left; margin:0 30px; color:blue; }
         #results { color:red; }
      </style>
   </head>

   <body>

      <ul>
         <li>First</li>
         <li>Second</li>
         <li>Third</li>
         <li>Fourth</li>
         <li>Fifth</li>
      </ul>

      <ul id = "results">
      </ul>
   </body>
</html>

これにより、次の結果が生成されます–