2016-03-04 58 views
0

,如果我有以下幾點:如何從jQuery的「身體」特定元素單擊事件

$('body').on('click', function() { 
    //alert($(this).attr('class')); alerts undefined because 'body' has no class 
}); 

我怎樣才能被點擊特定元素?

基本上我正在做的是,如果身體上的任何東西被點擊,做一件事,但如果它的一個特定元素,做別的事情。所以我檢查類,但是這不工作

類似:

$('body').on('click', function() { 
    if($(this).hasClass('specific') { 
    //do specific(); 
    } else { 
    //do generic(); 
    } 
}); 
+0

您需要查看**事件代表團**。基本上,你想要的是$('body')。on(「click」,「*」,function(){// stuff ...});'這表示,如果點擊了body的子元素並且匹配選擇器'*'(任何東西)比'//東西...'。檢查出http://stackoverflow.com/questions/8110934/direct-vs-delegated-jquery-on – chiliNUT

+0

可能的重複:http://stackoverflow.com/questions/8945825/jquery-on-click-document-get-clicked -element – Hardy

回答

2

使用event.target

$("body").on("click", function(event) { 
 
    alert(event.target); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<p>This is a paragraph</p> 
 

 
<button>This is a button</button>

https://api.jquery.com/event.target/

+0

你爲什麼要成爲這樣的人生救星? :) –

相關問題