Javascript 使用 jquery 循环遍历列表项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4511652/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:43:22  来源:igfitidea点击:

Looping through list items with jquery

javascriptjquery

提问by Grahame A

I have this block of code

我有这个代码块

listItems = $("#productList").find("li");

        for (var li in listItems) {
            var product = $(li);
            var productid = product.children(".productId").val();
            var productPrice = product.find(".productPrice").val();
            var productMSRP = product.find(".productMSRP").val();

            totalItemsHidden.val(parseInt(totalItemsHidden.val(), 10) + 1);
            subtotalHidden.val(parseFloat(subtotalHidden.val()) + parseFloat(productMSRP));
            savingsHidden.val(parseFloat(savingsHidden.val()) + parseFloat(productMSRP - productPrice));
            totalHidden.val(parseFloat(totalHidden.val()) + parseFloat(productPrice));

        }

and I'm not getting the desired results - totalItems is coming out as 180+ and the rest all NaN. I suspect its where i use var product = $(li);or perhaps with the expression on the loop itself. Either way - I need to loop through the <li>items in the <ul>labelled #productList

并且我没有得到想要的结果 - totalItems 是 180+,其余的都是 NaN。我怀疑它在哪里使用,var product = $(li);或者可能与循环本身的表达式一起使用。无论哪种方式 - 我都需要遍历标签中的<li>项目<ul>#productList

回答by lonesomeday

You need to use .each:

您需要使用.each

var listItems = $("#productList li");
listItems.each(function(idx, li) {
    var product = $(li);

    // and the rest of your code
});

This is the correct way to loop through a jQuery selection.

这是循环 jQuery 选择的正确方法。



In modern Javascript you can also use a for .. ofloop:

在现代 Javascript 中,您还可以使用for .. of循环:

var listItems = $("#productList li");
for (let li of listItems) {
    let product = $(li);
}

Be aware, however, that older browsers will not support this syntax, and you may well be better off with the jQuery syntax above.

但是请注意,较旧的浏览器不支持此语法,使用上面的 jQuery 语法可能会更好。

回答by girasquid

You can use eachfor this:

您可以each为此使用:

$('#productList li').each(function(i, li) {
  var $product = $(li);  
  // your code goes here
});

That being said - are you sure you want to be updating the values to be +1 each time? Couldn't you just find the count and then set the values based on that?

话虽如此 - 您确定要每次将值更新为 +1 吗?你不能只是找到计数然后根据它设置值吗?

回答by rcravens

Try this:

尝试这个:

listItems = $("#productList").find("li").each(function(){
   var product = $(this);
   // rest of code.
});

回答by wsanville

For a more definitive answer, you'll need to post some of your markup. You can simplify your jQuery quite a bit, like the following:

要获得更明确的答案,您需要发布一些标记。您可以大大简化您的 jQuery,如下所示:

$("#productList li").each(function() {
    var product = $(this);
    var productid = $(".productId", product).val();
    var productPrice = $(".productPrice", product).val();
    var productMSRP = $(".productMSRP", product).val();

    // the rest remains unchanged
}

回答by exoboy

Try this code. By using the parent>child selector "#productList li" it should find all li elements. Then, you can iterate through the result object using the each() method which will only alter li elements that have been found.

试试这个代码。通过使用 parent>child 选择器“#productList li”,它应该找到所有 li 元素。然后,您可以使用 each() 方法遍历结果对象,该方法只会更改已找到的 li 元素。

listItems = $("#productList li").each(function(){

        var product = $(this);
        var productid = product.children(".productId").val();
        var productPrice = product.find(".productPrice").val();
        var productMSRP = product.find(".productMSRP").val();

        totalItemsHidden.val(parseInt(totalItemsHidden.val(), 10) + 1);
        subtotalHidden.val(parseFloat(subtotalHidden.val()) + parseFloat(productMSRP));
        savingsHidden.val(parseFloat(savingsHidden.val()) + parseFloat(productMSRP - productPrice));
        totalHidden.val(parseFloat(totalHidden.val()) + parseFloat(productPrice));

    });

回答by Philipp

To solve this without jQuery .each()you'd have to fix your code like this:

要在没有 jQuery 的情况下解决此问题,.each()您必须像这样修复您的代码:

var listItems = $("#productList").find("li");
var ind, len, product;

for ( ind = 0, len = listItems.length; ind < len; ind++ ) {
    product = $(listItems[ind]);

    // ...
}

Bugs in your original code:

原始代码中的错误:

  1. for ... inwill also loop through all inherited properties; i.e. you will also get a list of all functions that are defined by jQuery.

  2. The loop variable liis not the list item, but the indexto the list item. In that case the index is a normal array index (i.e. an integer)

  1. for ... in还将遍历所有继承的属性;即,您还将获得由 jQuery 定义的所有函数的列表。

  2. 循环变量li不是列表项,而是列表项的索引。在这种情况下,索引是一个普通的数组索引(即整数)

Basically you are save to use .each()as it is more comfortable, but espacially when you are looping bigger arrays the code in this answer will be much faster.

基本上,您可以节省使用,.each()因为它更舒适,但特别是当您循环更大的数组时,此答案中的代码会快得多。

For other alternatives to .each()you can check out this performance comparison: http://jsperf.com/browser-diet-jquery-each-vs-for-loop

对于其他替代方案,.each()您可以查看此性能比较:http: //jsperf.com/browser-diet-jquery-each-vs-for-loop

回答by ronaldo

   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
   <script>
      $(document).ready(function() {
      $("form").submit(function(e){
          e.preventDefault();
       var name = $("#name").val();
       var amount =$("#number").val();
       var gst=(amount)*(0.18);
           gst=Math.round(gst);

       var total=parseInt(amount)+parseInt(gst);
       $(".myTable tbody").append("<tr><td></td><td>"+name+"</td><td>"+amount+"</td><td>"+gst+"</td><td>"+total+"</td></tr>");
       $("#name").val('');
       $("#number").val('');

       $(".myTable").find("tbody").find("tr").each(function(i){
       $(this).closest('tr').find('td:first-child').text(i+1);

       });

       $("#formdata").on('submit', '.myTable', function () {

                   var sum = 0;

          $(".myTable tbody tr").each(function () {
                    var getvalue = $(this).val();
                    if ($.isNumeric(getvalue))
                     {
                        sum += parseFloat(getvalue);
                     }                  
                     });

                     $(".total").text(sum);
        });

    });
   });

   </script>

     <style>
           #formdata{
                      float:left;
                      width:400px;
                    }

     </style>
  </head>


  <body>  

       <form id="formdata">  

                           <span>Product Name</span>
                           <input type="text" id="name">
                            <br>

                           <span>Product Amount</span>
                           <input type="text" id="number">
                           <br>
                           <br>
                           <center><button type="submit" class="adddata">Add</button></center>
       </form>
       <br>
       <br>

      <table class="myTable" border="1px" width="300px">
      <thead><th>s.no</th><th>Name</th><th>Amount</th><th>Gst</th><th>NetTotal</th></thead>

      <tbody></tbody>

      <tfoot>
             <tr>
                 <td></td>
                 <td></td>
                 <td></td>
                 <td class="total"></td>
                 <td class="total"></td>
             </tr>

      </tfoot>
      </table>

   </body>