使用jQuery将单个事件处理程序绑定到多个事件

19

我有一个包含不同onblur,onmousedown,onmouseup和onfocus功能的div。我想要最小化代码并在div内仅使用一个函数来处理所有功能状态。我想用jquery实现这个目标,换句话说,我想创建一个名为functionAll的函数,并将function1到function4及其鼠标状态放入其中,然后在div中只调用functionAll。我该怎么做?

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

1
为什么你想那样做? - The Scrum Meister
1个回答

50
你应该给这个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>

1
@Box9 不知何故我在文档中错过了这一点,这正是我正在寻找的。谢谢! - Brian Lacy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接