2016-03-04 57 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

你为什么要成为这样的人生救星? :) –

相关问题