First off, Eric didn't post the comment you're referring to. And if he had, I'd be inclined to cut him some slack. After all, Eric's English is *much* better than my Chinese (or whatever Eric's native language is).
Second, we all post something once in a while that offends another list member. I did it myself just yesterday - I offended a valuable contributor without meaning to! (Hi, MorningZ!)
As the wise lyricist from High School Musical once wrote, "We're all in this together!"
So have a very merry Christmas, and don't worry when someone writes something that doesn't quite come out the way they intended. :-)
-Mike
Ø this is a pretty stupid way to loop through a jQuery
object
Is it necessary to be insulting to be helpful, Eric? What was your
code like when you first began to write JS or jQuery? Always
perfect and mature, I'm sure…
Rick
From: jquery-en@googlegroups.com [mailto:jquery-en@googlegroups.com] On Behalf Of Eric Zhong
Sent: Wednesday, December 23, 2009 9:52 PM
To: jquery-en@googlegroups.com
Subject: Re: [jQuery] Re: how to access elements with index in for-loop
thank you very much, your way is better than mine !
2009/12/24 Šime Vidas <sime.vidas@gmail.com>
First of all, the "wrong" code is wrong, look.... this is your code:
$(function(){
var trs = $("#tb tr:not(:first)")
for( var i=0; i<$trs.length; i++ ) {
//$trs[i].find("td:eq(1)").attr("style","color:red"); //wrong
$trs.get(i).find("td:eq(1)").attr("style","color:red"); //wrong
}
})
1. you forgot to put semicolons at two places.....
$(function(){
var trs = $("#tb tr:not(:first)"); <-- HERE
for( var i=0; i<$trs.length; i++ ) {
//$trs[i].find("td:eq(1)").attr("style","color:red"); //wrong
$trs.get(i).find("td:eq(1)").attr("style","color:red"); //wrong
}
}); <-- HERE
2. You declared a variable named "trs" but you than use a varibale
named "$trs" which of course doesn't exist because you haven't
declared it...
$(function(){
var $trs = $("#tb tr:not(:first)");
for( var i=0; i<$trs.length; i++ ) {
//$trs[i].find("td:eq(1)").attr("style","color:red"); //wrong
$trs.get(i).find("td:eq(1)").attr("style","color:red"); //wrong
}
});
OK, now the code should work, right?
Well, no... because what the get(i) method does is it returns the DOM
element at index i from the $trs jQuery obect.... so after you do get
(i), you no longer have an jQuery object, and you cannot call the find
() method because it is not a property of DOM elements....
What you could do is encapsulate $trs.get(i) inside $() to get a
jQuery object based on the DOM element, so this code does work:
$($trs.get(i)).find("td:eq(1)").attr("style", "color:red");
However, this is a pretty stupid way to loop through a jQuery
object... a better way is to use the each() method:
$trs.each(function() {
$(this).find("td:eq(1)").attr("style", "color:blue");
});
No comments:
Post a Comment