【问题标题】:Binding a single event handler to multiple events with jQuery使用 jQuery 将单个事件处理程序绑定到多个事件
【发布时间】:2011-01-17 05:16:01
【问题描述】:

我有以下具有不同功能的 div,用于 onblur、onmousedown、onmouseup 和 onfocus。我想最小化代码,并且在 div 内只有一个函数调用用于所有函数状态。我想用 jquery 做到这一点,换句话说。我想创建一个名为 functionAll 的函数,并将所有 function1 放入函数 4 中,其中包含鼠标状态,然后在 Div 中使用 functionAll。我怎么能做这样的事情?

<div contentEditable="true"
     onblur="function1();"
     onmousedown="return function2(event);"
     onmouseup="function3();"
     onfocus="function4();">
    test test
</div>

【问题讨论】:

  • 你为什么要这样做?

标签: jquery events


【解决方案1】:

你应该在 div 上放一个 id,说“test”,然后:

$('#test').bind('blur mousedown mouseup focus', function (e) {
    // This is your combined function
    // Inside here you can use e.type to find out whether it was a
    // "blur", "mousedown", "mouseup", etc...
});

HTML 将如下所示:

<div id="test" contentEditable="true">
    test test
</div>

【讨论】:

  • @Box9 不知何故,我在文档中错过了这一点,这正是我想要的。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-18
  • 2020-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-22
相关资源
最近更新 更多