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