开发者

Selecting multiple cached elements

开发者 https://www.devze.com 2022-12-29 16:58 出处:网络
In jQuery you can select two elements by id like: $(\'#elem, #elem2\'); BUT What if you have cached the elem and elem2, and what to apply the same method/function to them both?

In jQuery you can select two elements by id like: $('#elem, #elem2');

BUT

What if you have cached the elem and elem2, and what to apply the same method/function to them both?

i.e.

$elem = $('#elem'); $elem2 = $('#elem2');

This obviously wont work:

$($elem, $elem开发者_如何转开发2)

Thanks!


Use the add method:

$elem.add($elem2).show();


Use the jquery data api http://docs.jquery.com/Data


This worked for me:

var element1 = $('#element1'),
    element2 = $('#element2'),
    element3 = $('#element3'),
    element4 = $('#element4');

$([element1[0], element2[0], element3[0], element4[0]]).my_function();  

and had after some performance testing a way better result than this:

element1.add(element2).add(element3).add(element4).my_function();
0

精彩评论

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

关注公众号