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

时间:2022-01-27 00:10:51

I have the following div with different functions for onblur, onmousedown, onmouseup, and onfocus.. I want to minimize the code and have only one function call inside div for all the function states. I want to do this with jquery So in other words. I want to create a function called functionAll and put all of function1 to function 4 with it's mouse state inside, then just use functionAll inside the Div. How can I do something like this?

我有以下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>

1 个解决方案

#1


48  

You should put an id on the div, say "test", then:

你应该在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...
});

The HTML will look like:

HTML将如下所示:

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

#1


48  

You should put an id on the div, say "test", then:

你应该在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...
});

The HTML will look like:

HTML将如下所示:

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