使用jquery循环遍历列表项 [英] Looping through list items with jquery
问题描述
我有这个代码块
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));
}
我没有得到预期的结果 - totalItems是出现在180+以及其他所有NaN。我怀疑它在哪里使用 var product = $(li);
或者可能使用循环本身的表达式。无论哪种方式 - 我需要遍历标有<$ c的< ul>
中的< li>
项目$ c> #productList
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
推荐答案
您需要使用 .each
:
You need to use .each
:
var listItems = $("#productList li");
listItems.each(function(idx, li) {
var product = $(li);
// and the rest of your code
});
这是循环选择jQuery的正确方法。
This is the correct way to loop through a jQuery selection.
在现代Javascript中,您还可以使用 的rel =noreferrer> 的引用/语句/ for ...循环:
In modern Javascript you can also use a for .. of
loop:
var listItems = $("#productList li");
for (let li of listItems) {
let product = $(li);
}
但请注意,旧浏览器不支持此语法,而您使用上面的jQuery语法可能会更好。
Be aware, however, that older browsers will not support this syntax, and you may well be better off with the jQuery syntax above.
这篇关于使用jquery循环遍历列表项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!