有没有办法(natvie JS 或 JQuery)在元素列表上注册相同的事件类型?
如果可能的话,我想避免在多个元素上重复注册一个事件,一次一个。
理想(伪)代码:
$({elem1, elem2, elem3}).on("keyup", function() {
// Do the same when each one of these elements gets focus
});
最佳答案
使用 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
});
关于JavaScript 一次性在多个元素上注册事件类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20378421/