简体   繁体   English

是否可以将两个单独的函数绑定到同一事件

[英]Is it possible to bind two separate functions to the same event

Basically I'd like to bind function A to all inputs. 基本上我想将函数A绑定到所有输入。 Something like this: 像这样的东西:

$('input').bind('change', function() { bla bla bla });

And then later I would like to bind something different in addition like this: 然后我想像这样绑定一些不同的东西:

$('#inputName').bind('change', function() { do additional processing..});

Is that possible? 那可能吗? Does it work? 它有用吗? Am I missing the syntax? 我错过了语法吗? Is that fine actually fine (meaning I have a bug elsewhere that's causing one of these not to bind)? 这样的罚款真的很好(这意味着我在其他地方有一个错误导致其中一个不能绑定)?

The short answer to your question is YES. 对你的问题的简短回答是肯定的。

If you wish to bind additional functionality to the change event of #inputName, your code sample should work. 如果您希望将其他功能绑定到#inputName的change事件,那么您的代码示例应该可以正常工作。

If you wish to alter the function that handles the event you can unbind all handlers of the change event before you rebind any new event handlers like so... 如果您希望更改处理事件的函数,您可以在重新绑定任何新事件处理程序之前取消绑定change事件的所有处理程序,如此...

$('#inputName').unbind('change');

but be careful... w/o trying this out I am unsure of any of the side affects. 但要小心......没有尝试这个,我不确定任何副作用。

为什么不创建一个同时调用它们的函数,然后将这个新函数绑定到事件?

In your code, one is input, and the other inputName, is that a typo? 在你的代码中,一个输入,另一个inputName,是一个错字?

Searched, there is a similar question here. 搜索过,这里有一个类似的问题

$(document).ready(function() {
  $("input").change(function() {
    console.log("function1");
  });

  $("input").change(function() {
    console.log("function2");
  });
});

assuming the above is resolved (ie you're trying to bind a function to the same object), yes, you can bind multiple event handlers to the same one. 假设上面已经解决(即你试图将一个函数绑定到同一个对象),是的,你可以将多个事件处理程序绑定到同一个。

to make your life easier, look into namespaces for this as well (so you can group event handlers for the same event). 为了让您的生活更轻松,也可以查看名称空间(这样您就可以为同一事件分组事件处理程序)。

It works fine to bind both. 它可以很好地绑定两者。 Where it gets slightly interesting is when you're trying to prevent default behavior by returning false. 它有点有趣的地方是你试图通过返回false来防止默认行为。 The bound functions cannot prevent each other from running that way, but they can prevent parent elements' event handlers from running. 绑定函数不能阻止彼此以这种方式运行,但它们可以阻止父元素的事件处理程序运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM