Array of selectors: for loop vs. $.each-Collection of common programming errors
Try
var arr = ['#home', '#news', '#tidy'];
$(arr.join(',')).toggle();
$(arr.join(‘,’)) => $(‘#home, #news, #tidy’), which selects all 3 elements then toggle() operates on all the selected elements.
If you do
$.each(arr, function(){
$(this).text("my id is " + this + ".");
});
the this
is actually a string object not a string primitive so what you get in return form $(this)
is a jQuery object wrapping a string object not the element that the selector will match. Adding a string primitive ''
to a string object gives you a string primitive which is why it works that way.
If you have to use $.each
better to use the arguments passed to the callback function, the first argument is the index of the array and the second is the value at the index.
$.each(arr, function(index, value){
$(value).text("my id is " + this + ".");
});
http://jsfiddle.net/2TPLD/
Originally posted 2013-11-09 19:43:44.