开发者

Way to access Array with jQuery objects

i've got an array like following

[jQuery('div#example1'), jQuery('div#example2'), jQuery('div#example3'), jQuery('div#e开发者_运维百科tcetera')]

Goal

elementArray = [jQuery('div#example1'), jQuery('div#example2'), jQuery('div#example3'), jQuery('div#etcetera')];

$(elementArray).remove();

//or

$(elementArray).css('border', '1px solid red');

I want them all to get the same treatment, with some function. The only way i know to access the elements is to loop trough the array.

Can someone help me out with a more efficient way to go about this?


Here you go:

$.each(elementArray, function(i, v) {
    v.remove();
});

When using $.each, the function runs for every array element (which is referenced by v).

Live demo: http://jsfiddle.net/XyRZE/


Update: You could use map to replace each jQuery object in the array with the DOM element object that's contained within it.

$(elementArray).map(function(i, v) { return v[0]; }).remove();

Live demo: http://jsfiddle.net/XyRZE/1/


Maybe you could select the items all together to one jQuery array

var myArray = $("div#wallItem303.wallItem, div#wallItem103.wallItem, div#wallItem323.wallItem");
myArray.css('border', '1px solid red');


You can target multiple elements in a jquery selector.

See jQuery multiple selector api.

jQuery('#wallItem303, #wallItem303').remove();

N.B if you have an id do not prefix it with the nodeName in the selector.


Here's the solution. The way you did is fine, however if you want to use a function, here you have:

$(elementArray).each(function(){
   $(this).css('border', '1px solid red');
   //Do whatever you want in this function
});

Hope this helps. Cheers

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜