Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/422.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在使用每个循环时获取每个父节点的ID_Javascript_Jquery - Fatal编程技术网

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

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

我可以实现获取每个循环中父节点的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
     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());
     });

     });