admin管理员组文章数量:1287579
I want to catch the click event on any elements of the page. But I can not catch a click on a specific page elements. See example /
$(function() {
$(".profile").on( "click","a", function() {
console.log(1);
return false;
});
// below not work
$("body").on( "click","*", function() {
console.log(2);
});
$("body").click(function() {
console.log(2);
});
$(window).click(function() {
console.log(2);
});
});
Why?
I want to catch the click event on any elements of the page. But I can not catch a click on a specific page elements. See example https://jsfiddle/rdnf5m1f/
$(function() {
$(".profile").on( "click","a", function() {
console.log(1);
return false;
});
// below not work
$("body").on( "click","*", function() {
console.log(2);
});
$("body").click(function() {
console.log(2);
});
$(window).click(function() {
console.log(2);
});
});
Why?
Share Improve this question edited Jan 15, 2016 at 21:11 Dmitriy Kupriyanov asked Jan 15, 2016 at 21:00 Dmitriy KupriyanovDmitriy Kupriyanov 4798 silver badges16 bronze badges 2-
1
Try wrapping that code in
$(function(){ // your code });
– area28 Commented Jan 15, 2016 at 21:02 - do not laugh at me. just try it – Dmitriy Kupriyanov Commented Jan 15, 2016 at 21:05
5 Answers
Reset to default 3Following what you need by "Capture all, Except some". Add a class 'nocapture' to the elements that you don't want to capture, and use the script:
jQuery('*:not(.nocapture)').on('click', function(e){
e.stopPropagation();
console.log('Element clicked', this);
})
When you return false
from a jQuery function, it executes stopPropagation
, which will prevent other handlers from executing. In this case I think you're looking for the following code.
$(document).on('click', function() {
console.log(2);
});
Wrap your code in some kind of ready handler like document
.
$(function() {
$("body").click(function() {
console.log(2);
});
});
Check this out
You can use e.target
properties to exclude a certain element type or class.
var tagsToExclude = 'a,div';
$(document).click(function(e) {
if(tagsToExclude.indexOf(e.target.nodeName.toLowerCase()) == -1)
alert('Clicked');
e.preventDefault();
});
Example : https://jsfiddle/DinoMyte/rdnf5m1f/4/
HTML
<body>
<div class="profile">
<a href="">Bla bla bla</a>
</div>
</body>
jQuery
$(window).on( "click", function() {
alert("click");
});
FIDDLE
本文标签: javascriptHow to detect any click on the pageStack Overflow
版权声明:本文标题:javascript - How to detect any click on the page? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741245882a2364864.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论