How can I bind many event handlers to one event using jQuery?

人盡茶涼 提交于 2019-12-06 12:35:38

问题


I'm experience strange behaviour with jQuery while trying to attach more than one event handler to a single event.

How would I bind two different event handlers, to the same event?

$(this).focus(function(){/*...*/});
$(this).focus(function(){/*...*/}); // replaces the previous one?

What am I missing?

Update

Do you know if it affects how event data is routed? It appears that adding a second event handler causes eventObject.data property to return undefined...?


Epilogue

The problem was somehow related to the way jQuery normalizes event handling and how the eventObject data property changed depending on routing, I had a delay timer at one point which read the property at a later time when it was undefined, I solved it by simply creating a local temporary for it.

obj.inputText.bind('blur', obj, function(e) {
    var div = e.data.div;
    setTimeout(function() { div.hide(); }, 333); // works!
    // setTimeout(function() { e.data.div.hide(); }, 333); // does not work
});

回答1:


That does work. I just double checked with this code:

$(document).ready(function() {
  $("#FirstName").focus(function() {
    console.log("focus1");
  });

  $("#FirstName").focus(function() {
    console.log("focus2");
  });
});

And it does produce two console messages when the input field is focused.

Are you positive that both your handlers aren't running?




回答2:


Can't you create on "master" function that calls all needed handlers?

$(this).focus( function() { function1();function2();etc..... });




回答3:


This should theoretically work, try if all handlers are fired using:

$(this).focus( function() { alert('handler1'); });
$(this).focus( function() { alert('handler2'); });
$(this).focus();


来源:https://stackoverflow.com/questions/702352/how-can-i-bind-many-event-handlers-to-one-event-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!