简体   繁体   English

来自jQuery对象的jQuery Selector

[英]jQuery Selector from jQuery objects

How can I listen to the onChange Event of multiple jQuery objects? 如何监听多个jQuery对象的onChange事件?

var el1= jQuery('input[type="checkbox"][name="x"]');
var el2= jQuery('input[type="checkbox"][name="y"]');
jQuery(el1, el2).change(function (e) {
    //....
});

Of course I could just put the 2 element selectors as a string into the .change function, but this is a simplified example. 当然我可以将2个元素选择器作为字符串放入.change函数中,但这是一个简化的例子。 I would like to work with the jQuery objects, not with string selectors. 我想使用jQuery对象,而不是使用字符串选择器。

This looked like a simple "let me google for you" question to me, but I have not been able to find a solution for the past hour. 对我来说这看起来像一个简单的“让我谷歌换你”的问题,但我找不到过去一小时的解决方案。

Try this 尝试这个

 var el1 = jQuery('input[type="checkbox"][name="x"]'); var el2 = jQuery('input[type="checkbox"][name="y"]'); $(document).on('change', [el1, el2], function() { console.log('multiple') }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label for="el1">Element 1</label> <input id="el1" type="checkbox" name="x" value="test1" /> <label for="el2">Element 2</label> <input id="el2" type="checkbox" name="y" value="test2" /> 

Also it is the first result of google and the main link is this 这也是谷歌的第一个结果,主要的链接就是这个

You can use add() or merge() method: 您可以使用add()merge()方法:

Add: 加:

el1.add(el2).change(function (e) {
    //....
});

Merge: 合并:

$.merge(el1, el2).change(function (e) {
    //....
});

你可以使用.add()

el1.add(el2).on('change', function () { /* body */ });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM