2016-08-11 196 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