开发者

appending and removing an image on toggle

开发者 https://www.devze.com 2023-01-30 06:36 出处:网络
I am appending which is positioned correctly when a li is clicked.My code works nicely although it keeps adding images to the page because i am not removing them when the li is toggled.Any ideas?

I am appending which is positioned correctly when a li is clicked. My code works nicely although it keeps adding images to the page because i am not removing them when the li is toggled. Any ideas?

$("#offering li").click(function() {                             
            $(this).find("ul").animate({height: "toggle"}, 500);
            $(this).append('<img width="286" height="15" class="offeringselected" alt="Selected" s开发者_Python百科rc="images/bg-offering-li-selected.png">');
            $(this).toggleClass('current');
    });


You can use the .toggle() event method, passing it two functions which will be alternated on clicks.

$("#offering li").toggle(function() {                             
        $(this).find("ul").animate({height: "toggle"}, 500);
        $(this).addClass('current')
               .append('<img width="286" height="15" class="offeringselected" alt="Selected" src="images/bg-offering-li-selected.png">');
},function() {                             
        $(this).removeClass('current')
               .children('img.offeringselected').remove();
});

Or perhaps it would be better to put the image in the page coming from the server, then just show and hide it.

To do this, you could use the other version of .toggle() that performs a show/hide.

$("#offering li").click(function() {                             
        $(this).find("ul").animate({height: "toggle"}, 500);
        $(this).toggleClass('current')
               .children('img.offeringselected').toggle(); // show/hide the img
});

Hardcode the image into the <li>, and give it an initial display:none in CSS.

0

精彩评论

暂无评论...
验证码 换一张
取 消