jquery event handler on multiple element variables

Is something like this possible? I have multiple variables set to DOM elements, and instead of hitting the DOM again to get set the event handlers, I want to use the variables I already have set.

var a = $("#foo");
var b = $("#bar");

a,b.on("click", function() {

});

Solution #1

You can use .add() to chain the cached elements.

var a = $("#foo");
var b  = $("#bar");

(a).add(b).on("click", function() {
  alert('Handler registered');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="foo">Foo</button>
<button id="bar">Bar</button>

在JQuery中,您可以使用与CSS中相同的符号来感染多个元素,只需使用逗号分隔它们即可。

$('#foo, #bar').on("click", function () {})

You can use an array as the argument to $() and it will create a new collection of everything in it. It doesn't hit the DOM again.

$([a, b]).on("click", function() {
    ...
});

var a = $('#foo');
var b = $('#bar');

$([a, b]).on("click", function() {
    alert('Does this work?');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="foo"> Foo </button>
<button id="bar"> Bar </button>
链接地址: http://www.djcxy.com/p/83470.html

上一篇: 哪个更好:字符串html生成或jQuery DOM元素创建?

下一篇: jQuery的多元素变量事件处理程序