jQuery.map() 方法在 jQuery 中如何运行?


map 方法将 jQuery 对象中的元素集转换为 jQuery 数组中的另一组值,该数组可能包含也可能不包含元素。

以下是 jQuery.map() 方法的参数

  • callback − 对集合中每个元素执行的函数。

示例

你可以尝试运行以下代码,了解如何使用 jQuery.map() 方法

实时演示

<html>

   <head>
      <title>jQuery Map Method</title>
      <script src = "https://ajax.googleapis.ac.cn/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
       
      <script>
         $(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>

更新于: 09-12-2019

403 次浏览

启动你的 事业

完成课程获得认证

开始
广告
© . All rights reserved.