jQuery - map( callback ) 方法



描述

map( callback ) 方法將 jQuery 物件中的一組元素轉換成 jQuery 陣列中的另一組值,這些值可能包含也可能不包含元素。

您可以使用此方法來構建值列表、屬性、css 值,甚至執行特殊、自定義的選擇器轉換。

語法

以下是使用此方法的簡單語法:

selector.map( callback )

引數

以下是此方法使用所有引數的描述:

  • callback − 在集合中每個元素上執行的函式。

示例

以下是一個簡單的示例,展示了此方法的用法:

<html>
   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript" 
         src = "https://tutorialspoint.tw/jquery/jquery-3.6.0.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>

這將產生以下結果:

jquery-traversing.htm
廣告
© . All rights reserved.