我试图获取被点击元素的父元素的 id。这个我试过了
$(window).click(function(event) {
alert("Clicked on " + event.target.id + ". Its parent is " + $(event.target).parent().attr("id"));
});
如果我有以下结构,它返回 Clicked on x。它的父级未定义
。
<div id="y">
<div id="x">X</div>
</div>
为什么不提供 parent 的 ID?
我也尝试过以下方法
$(this).closest("div").attr("id");
$(this).parent().attr('id')
最佳答案
$(document).on('click', '.clicked-element', function(){
parentElId = $(this).parent().attr('id');
// parentElId = $(this).parents('.custom-parent-class').attr('id'); // if you wan't the id from a different parent
});
关于javascript - 在 jQuery 中获取父元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16664617/