如何使用全局选择器响应除一个元素之外的所有单击事件? [英] How to use a global selector to respond to all click events except on one element?

查看:96
本文介绍了如何使用全局选择器响应除一个元素之外的所有单击事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个按钮:

<button id="button1">

通常我会写:

$("#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.

是否有一个选择器允许我定位文档中的所有其他可点击元素,除了 button1

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

推荐答案

我知道你已经接受了上面的答案,但我会强烈反对这一点。
你可以使用事件委托来做你想做的事情dom的开销要少得多。

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.

我知道.live()存在,但是太多的实时处理程序也会影响性能。我更喜欢事件委托旧样式。

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

演示此处

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

  function clickFn( ev ) {

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

  }

这篇关于如何使用全局选择器响应除一个元素之外的所有单击事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆