gpt4 book ai didi

javascript - 获取 id 父元素

转载 作者:行者123 更新时间:2023-11-28 05:24:54 25 4
gpt4 key购买 nike

当我点击 parent 时,我的功能开始工作得到 parent id ( tmp ),但是当我点击 child 时我的功能也有效,但返回 undefind .如何获得 parent id我点击什么并不重要 childparentparent 中的其他元素分区?

<div class="parent" id="tmp">
<div class="child"></div>
</div>
.parent {
width: 100px;
height: 100px;
}

.child {
width: 50px;
height: 50px;
}
'click .parent': function(e){
console.log($(e.target).attr("id")); // from MeteorJS framework , but same sense
}

最佳答案

在您的点击处理程序中,您应该使用 this 来引用正在处理事件的元素:

'click .parent': function(){
console.log(this.id);
}

通过使用 e.target,您定位的是发起事件的元素 - 在您描述的情况下,它是没有 .child 元素>id 属性。

如果由于 Meteor 施加的限制而无法使用 this 关键字,您可以改为使用 event 上的 currentTarget 属性,因为它应该具有相同的效果:

'click .parent': function(e){
console.log(e.currentTarget.id); // or $(e.currentTarget).prop('id')
}

关于javascript - 获取 id 父元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34006194/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com