首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在使用每个循环时获取每个父节点的ID

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

Stack Overflow用户
提问于 2016-02-26 13:52:23
回答 3查看 80关注 0票数 2

我可以实现获取每个循环中父节点的ID。但唯一的问题是,在我的解决方案中,我在控制台中遇到了这样的问题:

代码语言:javascript
复制
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

我期望的解决方案是:

代码语言:javascript
复制
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/

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-02-26 13:58:30

尝试像这样改写你的逻辑,

代码语言:javascript
复制
 $('#test .demo').each(function () {
       console.log(this.id);
     $("ul li", this).each(function(){
        console.log("   "+this.textContent)
     });
 });

演示

票数 3
EN

Stack Overflow用户

发布于 2016-02-26 13:59:59

您想要做的是在一个循环中执行一个循环,所以如下所示:

代码语言:javascript
复制
$('#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());
  });

 });

(这应该能起作用:)

票数 3
EN

Stack Overflow用户

发布于 2016-02-26 14:02:10

代码语言:javascript
复制
 $('.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/

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35653496

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档