javascript 使用 .add() 选择多个 jQuery 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14627330/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Select multiple jQuery objects with .add()
提问by Antony
Does the .add()
method allow selecting multiple objects in one go instead of adding one at a time?
该.add()
方法是否允许一次性选择多个对象而不是一次添加一个?
one.add(two).add(three).add(four).on("click", function() { });
The following variables are set in the way they do because each carries a different function.
以下变量按照它们的方式设置,因为每个变量都有不同的功能。
var one = $("#1");
var two = $("#2");
var three = $("#3");
var four = $("#4");
But what if I want to add an extra function that applies to all of these elements? Do I have to add them one by one?
但是如果我想添加一个适用于所有这些元素的额外函数怎么办?我必须一一添加吗?
I know you can select them all using $("#1,#2,#3,#4")
, but I just want to make use of the above variables.
我知道您可以使用 选择它们$("#1,#2,#3,#4")
,但我只想使用上述变量。
回答by Reinstate Monica Cellio
I'd prefer this array approach, purely for readability...
我更喜欢这种数组方法,纯粹是为了可读性......
$([one, two, three, four]).each(function() {
// your function here
});
回答by Jay Blanchard
You cannot add multiple objects in one go, for example:
您不能一次性添加多个对象,例如:
var groupThree = one.add(three, five); // will not work as expected
You could cache the added objects so that you only have to do the add one time - http://jsfiddle.net/X5432/
您可以缓存添加的对象,以便您只需添加一次 - http://jsfiddle.net/X5432/
var one = $("#1");
var two = $("#2");
var three = $("#3");
var four = $("#4");
var five = $("#5");
var groupOne = one.add(two).add(three).add(four);
var groupTwo = groupOne.add(five);
$('#first').click(function(e){
e.preventDefault();
groupOne.css({'background': '#00FF00'});
});
$('#second').click(function(e){
e.preventDefault();
groupTwo.css({'background': '#FF0000'});
});
But I like the array method better, this is just a different way of thinking about it.
但我更喜欢数组方法,这只是一种不同的思考方式。
回答by Anton
You could put them into an array like this
您可以将它们放入这样的数组中
var k = [one,two,three,four]
$.each(k,function(){
$(this).click(function(){
//Function here
});
});