我正在寻找一种更好的方法将多个事件绑定到jQuery中的单个元素。我试图避免编写多个$(元素).bind('event',...)或$(element).event(...)语句。
代码
// old way
var textbox = $('input');
$(textbox).focus(function() { ... }
$(textbox).blur(function() { ... }
// new way
$(textbox).extend({
focus: function() {
...
},
blur: function() {
....
}
});
不幸的是,这种实现不起作用。有人有更好的建议吗?谢谢。
答案 0 :(得分:9)
到目前为止,所有答案都假设您希望将相同的回调函数绑定到多个事件。如果情况并非如此,请考虑将.on()
与事件地图结合使用:
$('selector').on({
focus: function(e) {
// do something for focus
},
blur: function(e) {
// do something else entirely for blur
},
...
}
答案 1 :(得分:3)
试试这个:
$("textbox").bind('focus blur', function() {
// your code
});
对于jQuery 1.7+ bind
on
取代了$("textbox").on('focus blur', function() {
// your code
});
:
{{1}}
在这两种情况下,指定的函数将在第一个参数中列出的所有事件上运行。
答案 2 :(得分:3)
使用jQuery的.on()
方法:
$('input').on("focus blur", function () {
});
如果您需要根据事件执行条件逻辑:
$('input').on("focus blur", function (e) {
var whichEvent = e.type; // Will be "focus" or "blur"
});
答案 3 :(得分:0)
您可以使用
<element>.on("eventhandlers as commaseparated list",function(){})
如果您可以为所有这些处理程序使用一个函数,或
element.click(...)
.<anotherhandler>(...)
.<yetanother>(...)
如果您需要不同的功能。
.on()
是首选方式。
答案 4 :(得分:0)
// My way
var textbox = $('input');
$(textbox).on('focus blur', function(e){
if (e.type == 'focus'){
// do the focus stuff
} else if (e.type == 'blur'){
// do the blur stuff
}
}
这是未经测试的,但原则是
答案 5 :(得分:0)
您可以在jquery中使用bind函数:
例如:
$(textbox).bind('focus blur',function(){
//do something
});
答案 6 :(得分:0)
一旦在变量中保存了jQuery对象,就不需要一遍又一遍地将它转换为jQuery对象。您还可以“链接”事件绑定,因为它们会返回原始对象。
尝试这样的事情:
var $textbox = $('input'); // (Use a $ to mark variables that hold jQuery objects
$textbox
.on("focus", function() { ... })
.on("blur", function() { ... });
(另外,请确保检查您是否使用了正确的事件名称......我不知道我浪费了多少时间来寻找因为我为自己的名字编写事件所造成的错误。)< / p>