简体   繁体   English

使用 jQuery 遍历列表项

[英]Looping through list items with jQuery

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.并且我没有得到想要的结果 - totalItems 是 180+,其余的都是 NaN。 I suspect its where i use var product = $(li);我怀疑它在哪里我使用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无论哪种方式 - 我都需要遍历<ul>标记为#productList<li>

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 .. of loop:在现代 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 语法可能会更好。

You can use each for 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?话虽如此 - 您确定要每次将值更新为 +1 吗? Couldn't you just find the count and then set the values based on that?你不能只是找到计数然后根据它设置值吗?

Try this:尝试这个:

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

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
}

Try this code.试试这个代码。 By using the parent>child selector "#productList li" it should find all li elements.通过使用 parent>child 选择器“#productList li”,它应该找到所有 li 元素。 Then, you can iterate through the result object using the each() method which will only alter li elements that have been found.然后,您可以使用 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));

    });

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 ... in will also loop through all inherited properties; for ... in也将遍历所有继承的属性; ie you will also get a list of all functions that are defined by jQuery.即,您还将获得由 jQuery 定义的所有函数的列表。

  2. The loop variable li is not the list item, but the index to the list item.循环变量li不是列表项,而是列表项的索引 In that case the index is a normal array index (ie an integer)在这种情况下,索引是一个普通的数组索引(即整数)

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 : .each()

   <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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM