I would like to u开发者_如何学Pythonse an a tag to trigger appending hidden li items from a ul.
I have two uls, one that is visible as a list and another that is hidden. The hidden ul has lis that can be added to the visible list if you click a button.
I basically get the .html() for the hidden ul and then use the .append() to add them to the visible list.
This works find and dandy, but i want to treat the a link as a toggle and append/remove the hidden li's if they click it. Basically add them or remove them.
Any ideas on how to remove them on second click on the link?
Here is my jquery code:
// Add Related Products
$(".showProducts").click( function(){
var moreProductsItems = $(".moreRelatedProducts").html();
$("#myProductList").append(moreProductsItems);
$(".showProducts").toggleClass('hideProducts');
});
HTML code:
<a href="#" class="showProducts" onclick="return false;"></a>
<ul class="moreRelatedProducts" style="display:none;">
<li>Product Name</li>
<li>Product Name</li>
<li>Product Name</li>
<li>Product Name</li>
<li>Product Name</li>
<li>Product Name</li>
<li>Product Name</li>
</ul>
<div class="listBoxContainer2">
<ul id="myProductList">
<li>Product Name</li>
<li>Product Name</li>
</ul>
</div>
You can use the toggle-event, which accepts multiple handler functions for the click event.
$(".showProducts").toggle( function(){
var moreProductsItems = $(".moreRelatedProducts").html();
$("#myProductList").append(moreProductsItems);
$(".showProducts").toggleClass('hideProducts');
}, function() {
$("#myProductList").empty();
$(".showProducts").toggleClass('hideProducts');
});
It will toggle through the functions with each click. (You could pass more than two if desired.)
EDIT: To retain the original two in the list, instead of:
$("#myProductList").empty();
...you could do:
$("#myProductList").children().slice(2).remove();
Tip:
A better technique for link events.
<a href="#" class="showProducts" onclick="return false;"></a>
becomes:
<a href="javascript://" class="showProducts"></a>
精彩评论