我在 ul 中有许多 li 项目。我需要将所有 li 项添加到一个数组中,然后循环遍历该数组并对每个 li 中的值求和。
该值是该项目将花费的小时数。因此,第一项可能是 2 小时,第二项可能是 5 小时。
每 7.5 小时,我需要在每个里的日期字段中添加 1 天。因此,项目 1,2 和 3 将显示第 1 天。项目 4,5,6 和 7 将显示第 2 天,依此类推。
这是我到目前为止所拥有的:
列表数组:
var list = document.getElementById("dropArea").getElementsByTagName("li");
小时数:
var hrsArray = $("#sortable2 li").find("#hrsSpan").map(function () { return $(this).text() }).get();
var lengthArr = hrsArray.length;
for (var i = 0; i < lengthArr; i++) {
hrsArray[i] = hrsArray[i].replace("Hours - (", "");
hrsArray[i] = hrsArray[i].replace(")", "");
}
这是我计算的总小时数。我可以将“1”发送到每个 li 中的日跨度,但我不知道如何单独查看 li:
//Add all the hrs together to get the total
for (var i in hrsArray) {
total += hrsArray[i];
//alert(list[i].toString());
//Object found at this point, need to figure out how to send text to day span in it.
if (total / 7.5 <= 1) {
$('#sortable2 li').find('#day').html('1');
}
}
最佳答案
$('#sortable2 li').find('#day')
这将创建一个包含所有匹配对象的集合,以使用 .get(index) 检索特定对象。 http://api.jquery.com/get/
$('#sortable2 li').find('#day').get(i).html('1');
为了避免在每次迭代时重建集合,我会将其存储在循环外部的变量中。
//Add all the hrs together to get the total
var $dayFields = $('#sortable2 li').find('#day');
for (var i in hrsArray) {
total += hrsArray[i];
//alert(list[i].toString());
//Object found at this point, need to figure out how to send text to day span in it.
if (total / 7.5 <= 1) {
$($dayFields.get(i)).html('1');
}
}
编辑:
解决此问题的更好方法是循环遍历每个 li 而不是小时数组:
$("#sortable2 li").each(function() {
$(this).find("hrsSpan"); // This selects the hours field
$(this).find("day"); // This selects the day field in the same li
});
关于javascript - 将文本发送到数组中的特定 li,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28350165/