jquery显示/隐藏被忽略

时间:2013-01-17 19:09:52

标签: javascript jquery

我有一个用户可以“喜欢”的页面。一篇文章。

当页面首次加载时,我想显示他们是否已经喜欢过文章。

我用来向DOM添加html的代码是:

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();
}

&#34; wooo&#34;添加到html但显示/隐藏功能被忽略。 &#34; .like&#34;每篇文章都会显示课程。

我想要发生的是&#34; .like&#34;课程显示用户是否不喜欢文章和&#34; .unlike&#34;课程显示他们是否有。

我在这里错过了什么吗?

3 个答案:

答案 0 :(得分:2)

您是否将HTML添加到DOM?

如果没有,试试这个:

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

答案 1 :(得分:0)

您正在创建具有重复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>';

答案 2 :(得分:0)

得到它们,谢谢:

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,它更容易逐字显示或隐藏。

我不确定我是否也很好地解释了这个问题,为此道歉,但感谢一大堆的答案。