[英]How to find number of <ul> inside each div
我有一個這種形式的大文件[類似div的整個]。 我希望能夠選擇一個div
,找到其中的ul
的數量並遍歷每個div
以獲得其中每個li
值。
<div class="experiment">
<div class="experiment-number">5</div>
<ul class="data-values">
<li><div></div> 14</li>
<li><div></div> 15</li>
</ul>
<ul class="data-values">
<li><div></div> 16</li>
</ul>
</div>
我已經嘗試循環遍歷所有實驗div
,然后選擇ul
s,但它選擇頁面中的所有ul
,而不僅僅是當前div
下的ul
。
$('experiment ul').eq('$i');
您的HTML當前不正確,因為您只是啟動新的<div>
和<ul>
元素而不是關閉現有元素。 忽略這一點,因為修復它是微不足道的,我們將繼續討論真正的問題。
您需要選擇所有<div class="experiment">
元素,然后迭代它們。 為此,您可以使用.each()
函數。 它可能看起來像這樣:
var experiments = $('.experiment'); // all of them
experiments.each(function(i, val) { // will iterate over that list, one at a time
var experiment = $(this); // this will be the specific div for this iteration
console.log("Experiment: " + experiment.find('.experiment-number').text());
// outputs the experiment number
console.log("Experiment ULs: " + experiment.find('ul').length);
// number of <ul> elements in this <div>
var total = 0;
experiment.find('ul.data-values li').each(function() {
total += parseInt($(this).text(), 10);
});
console.log("Experiment total: " + total);
// outputs the total of the <li> elements text values
});
看看這個jsFiddle演示 。
得到div.experiment中的所有ul
var ul = $('.experiment').find('ul');
並獲取上面找到的每個ul內的所有li元素
ul.each(function(list) {
var li = $(list).find('li');
});
$('.experiment').each(function() {
var cnt = $(this).children('ul').length;
$(this).find('.experiment-number').text(cnt);
});
首先,您需要為每個DIV計算出正確的選擇器。
你想要的選擇器是:
".experiment"
請注意.
表示類選擇器。
這將允許您訪問每個DIV元素。 如果你想循環遍歷其中的每一個,你可以這樣做:
$(".experiment").each(function(){
var div = $(this);
var elementsInThisDiv = div.find("ul");
//you now have a list of all UL elements in the current DIV only
var numberOfElements = elementsInThisDiv.length;
//you now have a count of UL elements belonging to this DIV only
//you can loop the UL elements here
$(elementsInThisDiv).each(function(){
var ul = $(this);
//do something with the UL element
//like get the LI elements...
var liElements = ul.find("li");
});
});
重要提示 :HTML也存在錯誤,您需要使用</ul>
正確關閉<ul>
元素
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.