获取使用每个循环时每个父节点的 ID

Get the ID of the each parent node while using Each Loop

本文关键字:父节点 ID 循环 获取      更新时间:2023-09-26

我可以获取每个循环中父节点的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

检查我的小提琴:https://jsfiddle.net/5muotp9n/1/

试着这样重写你的逻辑,

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

https://jsfiddle.net/5muotp9n/1/