2015-02-05 101 views
0

我在ul中有許多li項目。我需要將所有的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」到每個立天跨度,但我無法弄清楚如何看李娜的以個人爲基礎:

//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
$('#sortable2 li').find('#day') 

這產生了一組與所有的匹配的對象,檢索特定對象使用獲得(索引)。 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'); 
    } 
} 

編輯:

一種更好的方式來處理,這將是遍歷每個立的,而不是幾小時的數組:

$("#sortable2 li").each(function() { 
    $(this).find("hrsSpan"); // This selects the hours field 
    $(this).find("day"); // This selects the day field in the same li 
}); 
2

當你做$('#sortable2 li').find('#day').html('1');你失去對jQuery對象找。您需要再次將其包裝在$()中。這是一個更簡單的方法,無需使用find。

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

下面有它的一個例子的工作http://jsfiddle.net/9nutmuvm/

+0

優秀,所以反正是有選擇的李項動態?這將發送1到每個列表項目 – 2015-02-05 17:31:54

+0

這將抓取ul中的每個li並在裏面添加'1' $(「#sortable2 li」)。html(1)' – mattfetz 2015-02-05 17:39:38

+0

是的,但我不想把'1 '在每一個裏,它會根據總小時數而改變 – 2015-02-05 17:41:53

相關問題