admin管理员组

文章数量:1302940

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?

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?

Share asked Jul 18, 2009 at 5:53 fritz carltonfritz carlton 716 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

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.

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');
    }

  }

The current CSS 3 Selectors Candidate Remendation 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.

本文标签: javascriptHow to use a global selector to respond to all click events except on one elementStack Overflow