简体   繁体   中英

Strange behavior in JavaScript

I have 2 elements - "span" (named "divLikedX") and "a" (named "aLikeX"). I have the following javascript (occurs clicking by "a"):

    function CommentLike(CommentID, aLink) {
        if (CommentID != null && CommentID > 0)
            $.post("/Home/LikeComment", { CommentID: CommentID },
            function () {
                //alert($("#divLiked" + CommentID).is(':visible'));
                /*alert($(aLink).text());*/if ($("#divLiked" + CommentID).is(':hidden')) {
                    $("#divLiked" + CommentID).show();
                    $("#aLike" + CommentID).text('Unlike');
                } else {
                    $("#divLiked" + CommentID).hide();
                    $("#aLike" + CommentID).text('Like');
                }
            });
        };

If I remove $("#aLike" + CommentID).text('Unlike'); and $("#aLike" + CommentID).text('Like'); strings I get the correct behavior. But with these strings it works correctly only first 2 clicks, after it alert($("#divLiked" + CommentID).is(':visible')) == "true" always. Why?

you do not seem to be the only one with the issue : cf http://forum.jquery.com/topic/hidden-visible-broken-in-ie8

The problems seems to append in IE8 when a display:none element has visible elements nearby. This seems to fool the jquery algorithm that detects :visible.

I can advice you to test with a class instead of :visible and :hidden :

if ($("#divLiked" + CommentID).hasClass('like')) {
      $("#divLiked" + CommentID).removeClass('like').show();
      $("#aLike" + CommentID).text('Unlike');
} else {
      $("#divLiked" + CommentID).addClass('like').show();
      $("#aLike" + CommentID).text('Like');
}

I hope this will help you,

Jerome Wagner

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM