Jquery显示/隐藏被忽略

jquery show/hide being ignored

本文关键字:隐藏 显示 Jquery      更新时间:2023-09-26

我有一个页面,用户可以在其中"喜欢"一篇文章。

当页面第一次加载时,我想显示他们是否已经喜欢了一篇文章。

我用来添加html到DOM的代码是:
html += '<div class="gl_like">';
html += '<a href="#" class="like" id="'+image.article_id+'"><div class="bLike" title="Like this article"></div></a>';
html += '<a href="#" class="unlike" id="'+image.article_id+'"><div class="bUnlike" title="Unlike this article"></div></a>';
html += '</div>';

现在我正在检查API返回的内容,以确定用户是否已经喜欢了一篇文章

if(image.numLikes<1){
$('.like').show();
$('.unlike').hide();
html += 'wooo'; // to test the code works, it does
} else {
$('.like').hide();
$('.unlike').show();
}

"wooo"被添加到html中,但是show/hide函数被忽略了。"。就像" class "显示在每篇文章上。

我想要发生的是"。比如"类显示用户是否喜欢一篇文章和"。不像" class "显示它们是否有。

我错过了什么吗?

你把html添加到DOM的任何地方吗?

如果没有,试试这个:

$(html).find('.like').show();
$(html).find('.unlike').hide();

您正在创建具有重复id属性的元素:id="'+image.article_id+'"您需要更改这一点,使它们是唯一的,这是必需的。例:

html += '<div class="gl_like">';
html += '<a href="#" class="like" id="like_'+image.article_id+'"><div class="bLike" title="Like this article"></div></a>';
html += '<a href="#" class="unlike" id="unlike_'+image.article_id+'"><div class="bUnlike" title="Unlike this article"></div></a>';
html += '</div>';

知道了,谢谢:

if(image.numLikes<1){
    html += '<a href="#" class="like" id="'+image.article_id+'"><div class="bLike" title="Like this article"></div></a>';
    html += '<a href="#" class="unlike" id="'+image.article_id+'" style="display:none;"><div class="bUnlike" title="Unlike this article"></div></a>';
    } else {
    html += '<a href="#" class="like" id="'+image.article_id+'" style="display:none;"><div class="bLike" title="Like this article"></div></a>';
    html += '<a href="#" class="unlike" id="'+image.article_id+'"><div class="bUnlike" title="Unlike this article"></div></a>';
    }

直接显示或隐藏比使用show/hide更容易。

我也不确定我把问题解释得很好,很抱歉,但是非常感谢你的回答。