I don't understand what happens when you do a chain of .show()s like that. Nor did I write this code or have an idea of how to figure out what is happening here. Hence this question.
// Remove favorite category
$(".FavoriteRemove").click(function() {
var cat = $(this).parents(".Category"); //the parent of the clicked item is the category/bundle
var catid = $(this).attr("catid"); //the id tag on the clicked item is the BundleID
$.post(开发者_高级运维$(this).attr("href"), function() { //the href tag is the post URL for adding a favorite
cat.remove(); //here we remove the category/bundle
//*** WHAT IS THIS DOING? v
$(".Category[catid=" + catid + "]").show().parent().show();
//*** NO THAT UP THERE ^
if ($(".FavoriteCategories div").length == 0)
$(".FavoriteCategories").hide();
//bindCategories();
});
return false;
});
Can someone describe what this means? I am aware the target is class 'Category' with an attribute matching the ID but I don't understand what the chain of functions means.
Thanks.
- First
show()
(docs) the element with the classCategory
, and thecatid
attribute with value of the given variable. - Then traverse up to its parent using the
parent()
(docs) method. - Then
show()
(docs) the parent.
"Showing" means setting its display
style property from none
to its initial (or default) value, like block
.
In JavaScript you can directly "use" the return value of a function call without assigning the value to a variable. Here is a stripped down example:
var john = {
me: function() {
alert('...John');
}
}
var foo = {
call: function() {
alert('You called..');
return this; // <- note that an object is returned
}, // (in this case foo itself but could be any object)
callSomeoneElse: function() {
alert('You called..');
return john; // <- note that an object is returned
},
me: function() {
alert('...me');
}
}
foo.call().me()
foo.callSomeoneElse().me()
Now to your method call:
If you have
$(selector).show()
then the selected elements will be shown. show
returns again the set of selected elements (the same elements selected by $(selector)
). This allows us to call another method on them: parent()
selects (returns) the parent nodes of these elements (so we have a different set now) and the second show()
operates on this new (parent) set (and returns the parent set).
So
$(selector).show().parent().show()
will show the selected elements and their parents.
The whole concept is called fluent interface and is achieved through method chaining.
$(".Category[catid=" + catid + "]").show().parent().show();
It will show (make visible) the element(s) with a class Category
and a catid set to the variable catid, and it will show the parent element:
<div>
<span class="Category" catid="1"></span>
</div>
In this case it would show both the span and the div.
精彩评论