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
Add a ment  | 

5 Answers 5

Reset to default 3

Following 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