我的函数在单击parent并获取parent id ( tmp )时开始工作,但当我单击child时,我的函数也可以工作,但返回undefind。如何获得parent id并不重要,我单击了child、parent或parent div中的其他项目?
<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
} 发布于 2015-11-30 19:24:14
在单击处理程序中,应该使用this引用正在处理该事件的元素:
'click .parent': function(){
console.log(this.id);
} 通过使用e.target,您的目标是引发事件的元素--在您描述的情况下,该元素将是没有id属性的.child元素。
如果由于Meteor施加的限制而无法使用this关键字,则可以在event上使用currentTarget属性,因为它应该具有相同的效果:
'click .parent': function(e){
console.log(e.currentTarget.id); // or $(e.currentTarget).prop('id')
} 发布于 2015-11-30 19:19:52
尝试:
$('.parent').click(function(){
console.log($(this).attr('id'));
//console.log($(this)[0].id)
});或
$('.parent').click(function(e){
console.log(e.currentTarget.id);
});或
$('.parent').click(function(e){
console.log(e.delegateTarget.id);
});发布于 2015-11-30 19:22:08
这是你想要的吗?
$(function() {
$('div').click(function(e) {
var id = $(e.target).parent().attr('id');
if (typeof id === 'undefined') {
//return current element as this is a parent
console.log($(e.target).attr('id'));
} else {
//return parent's id
console.log(id);
}
});
});.parent {
width:100px;
height:100px;
background: red;
}
.child {
width:50px;
height:50px;
background: black;
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent" id="tmp">
<div class="child">
</div>
</div>
https://stackoverflow.com/questions/34006194
复制相似问题