将文本发送到数组中的特定li

时间:2015-02-05 17:20:00

标签: javascript jquery asp.net webforms jquery-ui-sortable

我有一些ul的li项目。我需要将所有li项添加到数组中,然后循环遍历数组并将每个li中的值相加。

该值是指该项目所需的小时数。因此第一项可能是2小时,第二项可能是5小时。

每7.5小时,我需要在每个li中添加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');
    }
}

2 个答案:

答案 0 :(得分:2)

执行$('#sortable2 li').find('#day').html('1');时,您会在查找中丢失jquery对象。您需要再次将其包装在$()中。这是一种更简单的方法,无需使用find。

$("#sortable2 #day").html(1)

下面是一个工作http://jsfiddle.net/9nutmuvm/

的例子

答案 1 :(得分:2)

$('#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
});