using prepend and remove
I am using .prepend()
and .remove()
to show menu items in the order a user clicks them.
$(document).开发者_Python百科ready(function()
{
$('#item1').click(function()
{
$('#item1_content').remove();
$('.menu_item_content').prepend('<div id="item1_content">The Box For Menu Item One</div>');
});
$('#item2').click(function()
{
$('#item2_content').remove();
$('.menu_item_content').prepend('<div id="item2_content">The Box For Menu Item Two</div>');
});
});
I use .remove()
to remove the item if it already exists and the .prepend()
to put it at the top of the container div
In this way the user can show as many or as few of the menu items as they want at once and in the order they click them but duplicates should not appear.
For example. The user could click MenuItem3 then MenuItem1 Then MenuItem2 and the items would display below:
Item2 Item1 Item3
The first half of my script works #item1 but #item2 does not, it just keeps making duplicates.
Also if I do #item1 then #item2 then #item1 again I get a duplicate.
What am I doing wrong here? Is there a better way to do this?
You actually don't need the remove() function at all. This should work nicely, assuming that your HTML is similar:
<div class="menu_item_content">
<div id="item1">
<div id="item1_content">MenuItem1</div>
</div>
<div id="item2">
<div id="item2_content">MenuItem2</div>
</div>
<div id="item3">
<div id="item3_content">MenuItem3</div>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
jQuery(document).ready(function() {
jQuery('.menu_item_content').children().click(function() {
jQuery('.menu_item_content').prepend(jQuery(this));
});
});
</script>
精彩评论