How to use a global selector to respond to all cli

2019-07-13 03:49发布

问题:

If I have a button:

<button id="button1">

Normally I would write:

$("#button1").click(function ()
{    
    //do something
}

But I want to define a function that responds to all click events except when someone clicks on this button.

Is there a selector that would allow me to target all other clickable elements in the document except button1?

回答1:

I know you have accepted the answer above but I would advise strongly against this. You can use event delegation to do what you want with a lot less overhead to the dom.

I know .live() exists but too many live handlers also impact performance. I prefer event delegation old style.

Demo here

$(function(){
    $('body').click( clickFn );
  });

  function clickFn( ev ) {

    if (ev.target.id != 'button1' ){
       //do your stuff
       console.log('not a #button1 click');
    }

  }


回答2:

You could use the :not selector:

$('button:not(#button1)').click(function(){
  //Do something
});

The above selector will match all the button elements, except the one with id = "button1".

If you want really to select all the elements under the body tag, you can use the "All" (*) selector, and also exclude the elements with :not(selector) or .not(expr):

$('body *:not(#button1)').click(function(){
  //Do something
});

Or

$('body *').not('#button1').click(function(){
  //Do something
});

If you do so, you could have some event bubbling or propagation issues, you can handle this with the event.stopPropagation function.



回答3:

The current CSS 3 Selectors Candidate Recommendation defines the :root pseuedo class.

The :root pseudo-class represents an element that is the root of the document. In HTML 4, this is always the HTML element.

You could attach an event listener to the root and then check which element received the click. If it's the element you want to ignore return, otherwise do whatever it is you want to do.