简体   繁体   English

获取ID父元素

[英]Get id parent element

I have function that start working when I click on parent and get parent id ( tmp ), but when I click on child my function works too but return undefind . 当我单击parent并获取parent idtmp )时,我的函数开始工作,但是当我单击child我的函数也起作用,但返回undefind How to get parent id doesn't matter on what I click child or parent or other elemnts in parent div ? 在我单击childparentparent div中的其他元素时,如何获取parent id无关紧要?

<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
} 

try: 尝试:

$('.parent').click(function(){
  console.log($(this).attr('id'));
  //console.log($(this)[0].id)
});

or 要么

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

or 要么

$('.parent').click(function(e){
  console.log(e.delegateTarget.id);
});

In your click handler you should use this to refer to the element that is handling the event: 在点击处理程序中,您应该使用this来引用处理事件的元素:

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

By using e.target you're targeting the element which originated the event - which in the cases you describe would be the .child element which has no id attribute. 通过使用e.target您可以定位.child事件的元素-在您描述的情况下,该元素将是不具有id属性的.child元素。

If you are unable to use the this keyword due to restrictions imposed by Meteor, you could instead use the currentTarget property on the event , as it should have the same effect: 如果由于Meteor施加的限制而无法使用this关键字,则可以对event使用currentTarget属性,因为它应该具有相同的效果:

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

Is this what you want? 这是你想要的吗?

 $(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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM