javascript - 在 jquery 中使用 .parent()

标签 javascript jquery

我正在尝试循环几个 div。

代码:

$(".tree  div ").each(function () {
    var _searchthis = $(this);
    var mySearchDiv = _searchthis.parent('div').attr('id');
    console.log("this is ID : " + $(this).attr('id'));
    console.log("this is parentID : " + mySearchDiv);
});

如果是 ID,我会获取该值。但它不会返回 .parent('div').attr('id')

我得到“未定义”。

编辑:

当我使用 .closest() 而不是 .parent() 时,我仅获得 $(this) 的 ID。 .parents('div').first().attr('id') 也会返回“undefined”。

$(".tree li div ").each(function (){
....
}

这是一次绝望的尝试。

HTML 代码更像是:http://jsbin.com/yilaw/1/edit

======================================

已解决。我的 HTML 结构有问题。谢谢大家。

最佳答案

尝试将代码更改为:

_searchthis.parents("div").eq(0).attr('id');

关于javascript - 在 jquery 中使用 .parent(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24780042/

相关文章:

javascript - 无法使用 ui 路由器注入(inject) View

javascript - 如果没有 $timeout,UI 路由加载微调器将无法工作

jquery - HTML5 离线谷歌地图访问

javascript - 如何在不调用函数的情况下更改 jQuery 中的执行上下文

html - Jquery 下一个按钮不适用于图片库

javascript - MongoDB:更新集合中所有文档中的嵌套数组字段

JavaScript 计算器 5 + 5 = 55?

javascript - 防止垂直滚动超出 div

jquery - 可折叠的 Bootstrap 表格行

javascript - 如何使用HTML数据属性返回对象数据?