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
?
3 Answers
Reset to default 7You 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 theHTML
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.
版权声明:本文标题:javascript - How to use a global selector to respond to all click events except on one element? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741715095a2394061.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论