JavaScript一次性在几个元素上注册一个事件类型

时间:2013-12-04 14:49:47

标签: javascript jquery events bind accessibility

有没有办法(natvie JS或JQuery)在元素列表中注册相同的事件类型?

如果可能,我想避免重复在多个元素上注册一个事件,一次一个。

理想(伪)代码:

$({elem1, elem2, elem3}).on("keyup", function() {
    // Do the same when each one of these elements gets focus
});

2 个答案:

答案 0 :(得分:6)

使用jQuery:

对于缓存元素引用,您可以使用add

$(elem1).add(elem2).add(elem3).on("keyup", function() {
    // Do the same when each one of these elements gets focus
});

或者,按类名等选择多个元素:

$(".one, .two, .three").on("keyup", function() {
    // Do the same when each one of these elements gets focus
});

如果您有一个动态的缓存元素引用数组:

var cache = [elem1, elem2, elem3]; // could be any length, added to dynamically etc...

var $collection = $(); // new empty jQuery object

// add each item to the jQuery object
for(var i = 0; i < cache.length; i++) {
    $collection = $collection.add(cache[i]);
}

$collection.on("keyup", function() {
    // Do the same when each one of these elements gets focus
});

答案 1 :(得分:1)

你可以,

$("#id1, .class2, #id3").on("keyup", function() {
    //code
});