Javascript 在使用每个循环时获取每个父节点的ID
我可以实现获取每个循环中父节点的ID。但唯一的问题是在我的解决方案中,我在console中得到了如下结果:Javascript 在使用每个循环时获取每个父节点的ID,javascript,jquery,Javascript,Jquery,我可以实现获取每个循环中父节点的ID。但唯一的问题是在我的解决方案中,我在console中得到了如下结果: test-1 // test-1 id Test1 test-1 // test-1 id Test2 test-1 // test-1 id Test3 test-2 // test-2 id Test1 test-2 // test-1 id Test2 test-3
test-1 // test-1 id
Test1
test-1 // test-1 id
Test2
test-1 // test-1 id
Test3
test-2 // test-2 id
Test1
test-2 // test-1 id
Test2
test-3
Test1
我期望的解决方案是:
test-1 // test-1 id
Test1
Test2
Test3
test-2 // test-2 id
Test1
Test2
test-3 // test-3 id
Test1
检查我的小提琴:试着像这样重写你的逻辑
$('#test .demo').each(function () {
console.log(this.id);
$("ul li", this).each(function(){
console.log(" "+this.textContent)
});
});
你要做的是在一个循环中做一个循环,比如:
$('#test ul').each(function () {
var parents = $(this).parents('.demo').attr('id');
console.log("Parent : " + parents);
$(this).find('li').each(function(){ //for each li
console.log($(this).html());
});
});
这应该可以做到:)
$('.demo').each(function () {
var parents = $(this).attr('id');
console.log(parents);
$(this).find("li").each(function(){
console.log(" "+$(this).text());
});
});