我正在尝试循环几个 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/