gor*_*orn 0 javascript jquery events accessibility bind
有没有办法(natvie JS或JQuery)在元素列表上注册相同的事件类型?
如果可能的话,我想避免重复在几个元素上注册事件,一次一个.
理想(伪)代码:
$({elem1, elem2, elem3}).on("keyup", function() {
// Do the same when each one of these elements gets focus
});
Run Code Online (Sandbox Code Playgroud)
使用jQuery:
对于缓存的元素引用,您可以使用add:
$(elem1).add(elem2).add(elem3).on("keyup", function() {
// Do the same when each one of these elements gets focus
});
Run Code Online (Sandbox Code Playgroud)
或者,按类名等选择多个元素:
$(".one, .two, .three").on("keyup", function() {
// Do the same when each one of these elements gets focus
});
Run Code Online (Sandbox Code Playgroud)
如果您有一个动态的缓存元素引用数组:
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
});
Run Code Online (Sandbox Code Playgroud)