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.com/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.