2016-08-11 198 views
1

我有这样的HTML代码:起泡避免嵌套元素

<td class="myclass"> 
    <span> 
     <span>xxxx</span> 
    </span> 
    <span>xxxx</span> 
    <span>xxxx</span> 
</td> 

我附加click事件与类的元素“MyClass的”传递机能的研究回调。在这个函数中,我收到了event.target中的任何元素,但我想要的元素是td。 ¿我是否可以避免冒泡以便始终获得目标或事件中的td?

非常感谢

回答

2

使用this上下文中handler-function

$('.myclass').on('click', function() { 
 
    console.log(this); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
 
<table> 
 
    <tr> 
 
    <td class="myclass"> 
 
     <span> 
 
     <span>xxxx</span> 
 
     </span> 
 
     <span>xxxx</span> 
 
     <span>xxxx</span> 
 
    </td> 
 
    </tr> 
 
</table>

或者e.currentTarget

当事件遍历DOM时,标识事件的当前目标。它始终引用事件处理程序已附加的元素,而不是event.target,它标识事件发生的元素。

$('.myclass').on('click', function(e) { 
 
    console.log(e.currentTarget); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
 
<table> 
 
    <tr> 
 
    <td class="myclass"> 
 
     <span> 
 
     <span>xxxx</span> 
 
     </span> 
 
     <span>xxxx</span> 
 
     <span>xxxx</span> 
 
    </td> 
 
    </tr> 
 
</table>

+0

我忘了让知道,因为我需要这样附加的事件,我不能用这个:( 'MyClass的 ')。$在(' 点击',myFunction的);一旦在我的功能“这个”是文件。 – MKP

+0

@MKP - 第二种方法呢? – Rayon

+0

“this”或“e.currentTarget”是回调函数中的文档本身。 Thx为您提供帮助。 – MKP