开发者

Apply CSS to multiple elements in variables

开发者 https://www.devze.com 2023-02-06 04:33 出处:网络
I have this: var $e1 = $(\'#e1\'); var $e2 = $(\'#e2\'); var $e3 = $(\'#e3\'); This doesn\'t work: var $all = [$e1, $e2, $e3];

I have this:

var $e1 = $('#e1');
var $e2 = $('#e2');
var $e3 = $('#e3');

This doesn't work:

var $all = [$e1, $e2, $e3];
$($all).css('background', '开发者_StackOverflow社区#ff0000');

How should I do this, while reusing $el1, $el2, $el3?

I don't want to do:

$('#e1, #e2, #e3')

This is probably very simple to do, but I don't know what to search for to find out.


You can do this:

var $all = $e1.add($e2).add($e3);

Or this (looks a little obtuse, but it's the correct way - you have to extract the node from the jQuery object first with [0]):

var $all = $([$e1[0], $e2[0], $e3[0]]);

Note: in my examples, $all is already a jQuery object, so you don't need to wrap it again like this: $($all). Just do:

$all.css('background', '#ff0000');


Edit: even better:

var $e1 = $('#e1');
var $e2 = $('#e2');
var $e3 = $('#e3');
var all = $e1.add($e2).add($e3);
all.css('background', '#ff0000');


$e1.add($e2).add($e3)

is another way of merging different elements/jQuery objects.

Reference: .add()


Edit: wrap array in jQuery instance and iterate through its elements

all = [$e1, $e2, $e3];

$(all).each(function(index, element){
   element.css('background', '#ff0000');
})


Well if you don't want to use a selector, apply the style to each element of the array.

for(i = 0; i < $all.length; i++)
    $all[i].css('background', '#ff0000');


you can do what you have in your example:

var $all = [$e1, $e2, $e3],
    i = $all.length;

for(; i--;) {
    $all[i].css('background', '#f00');
}


It seems you ca do just this:

$(deleteBtn).add(copyBtn).add(moveBtn).css('background', 'white');

As it says here http://api.jquery.com/add/

0

精彩评论

暂无评论...
验证码 换一张
取 消