jquery - Array of selectors: for loop vs. $.each -


given following array of selectors (each of display: none in our css) , loop:

var arr = ['#home', '#news', '#tidy'];  (i=0;i<=arr.length;i++){     $(arr[i]).toggle(); } 

what equivalent using $.each ( , presumably $(this) )?

edit

ok understand using join:

var s = arr.join(); $(s).toggle(); 

i did not realize "toggle many other jquery methods calls each method internally there no need use each" +1 @undefined, however...

the question original put forth because when i:

$.each(arr, function(){     $(this).text("my id " + + "."); }); 

i undefined (!) errors. (ok fair there .toggle , .insertafter etc., i'm attempting simplify) why above not equivalent to:

$('#home').text('my id #home.'); $('#news').text('my id #news.'); $('#tidy').text('my id #tidy.'); 

?

edit 2

ok syntax issue - $(this) requires prepending '' +:

$('' + this).text('my id ' + + '.') 

is there rule when $(this) requires such treatment?

try

var arr = ['#home', '#news', '#tidy']; $(arr.join(',')).toggle(); 

$(arr.join(',')) => $('#home, #news, #tidy'), selects 3 elements toggle() operates on selected elements.


if do

$.each(arr, function(){     $(this).text("my id " + + "."); }); 

the this string object not string primitive in return form $(this) jquery object wrapping string object not element selector match. adding string primitive '' string object gives string primitive why works way.
if have use $.each better use arguments passed callback function, first argument index of array , second value @ index.

$.each(arr, function(index, value){     $(value).text("my id " + + "."); }); 

http://jsfiddle.net/2tpld/


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -