允许先触发其他绑定元素事件

Allow other bound element events to trigger first?

本文关键字:元素 事件 绑定 其他 许先触      更新时间:2023-09-26

是否有一种方法允许其他绑定事件到同一对象(例如:文本框)触发/触发第一?

假设两个事件绑定到同一个文本框。两个keyup事件。在我的例子中,有一个插件绑定它自己的事件,但是代码编写的方式,我的先被绑定。我可不想我的先着火。

$("#firstname").keyup(function() {
    // ...is there anyway to allow the other keyup event to fire first, from here?
    // do my work here...
}
$("#firstname").keyup(function() {
    // the plugin work.
}

我需要使用keyup,已经有了key down事件

你真的应该重写你的代码,只有一个keyup绑定到那个事件,但如果这是不可行的,你可以用信号量来做,把你的功能从绑定中分离出来,这样它就可以从绑定中调用。

var semaphore = 0; // on init
$("#firstname").keyup(function () { // this one should run first
 semaphore++;
 if (semaphore === 0) {
    first_action();
 }
}
$("#firstname").keyup(function () { // this one should run second
 if (semaphore > 1) { // you know the first event fired
   second_action();
 }
 else if (semaphore < 1) {
   first_action();
   second_action();
   semaphore++; 
 }
}