我可以实现获取每个循环中父节点的ID。但唯一的问题是,在我的解决方案中,我在控制台中遇到了这样的问题:
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检查我的Fiddle:https://jsfiddle.net/5muotp9n/1/
发布于 2016-02-26 13:58:30
尝试像这样改写你的逻辑,
$('#test .demo').each(function () {
console.log(this.id);
$("ul li", this).each(function(){
console.log(" "+this.textContent)
});
});发布于 2016-02-26 13:59:59
您想要做的是在一个循环中执行一个循环,所以如下所示:
$('#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());
});
});(这应该能起作用:)
发布于 2016-02-26 14:02:10
$('.demo').each(function () {
var parents = $(this).attr('id');
console.log(parents);
$(this).find("li").each(function(){
console.log(" "+$(this).text());
});
});https://stackoverflow.com/questions/35653496
复制相似问题