Jquery: can you explain this line of code to me? help me to understand it, or give references to where I can learn about it
Jquery 1.6 just came out, I grabbed this code from the .is
api page.
I j开发者_JAVA百科ust had a few questions on a piece of code I saw there:
1) why is return
needed? Isn't there another way to write this that's easier? I mean, i've never used return
when I've written anything Jquery. Obviously I haven't written anything advanced and i'm still just learning. Why would you need it, when would you use it? and is there another way to do the same thing?
2) $('strong', this)
means "any <strong>
elements in this element." right? and that full line would read "give me the element that has 2 strong elements within this"? right? or? (i think i have that wrong.) isn't there another way to write this? i've only seen this used a few times.
$("li").click(function() {
var $li = $(this),
isWithTwo = $li.is(function() {
return $('strong', this).length === 2;
});
if ( isWithTwo ) {
$li.css("background-color", "green"); } else {
$li.css("background-color", "red"); } });
why is return needed?
Look at the documentation for is
. The point is that the function will return either true or false.
$('strong', this)
means "any<strong>
elements in this element." right?
yes
and that full line would read "give me the element that has 2 strong elements within this"?
No. It will be "If there are 2 strong elements, return true, otherwise return false"
return $('strong', this).length === 2;
If this
has 2 <strong>
elements, return true
. Otherwise, return false
.
精彩评论