2013-01-17 107 views
0

我有一個頁面,用戶可以'喜歡'一篇文章。jquery顯示/隱藏被忽略

頁面第一次加載時我想顯示它們是否已經喜歡文章。

我使用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中,但顯示/隱藏功能被忽略。每個文章都會顯示「.like」類。

我想要發生的是「.like」類顯示如果用戶不喜歡文章和「.unlike」類顯示,如果他們有。

我在這裏錯過了什麼嗎?

+1

您需要在將HTML添加到DOM之後運行if語句 – ManseUK

+0

您是否總是「喜歡」和「不像」? – Wolf

+0

@ManseUK可能有15篇文章在頁面上,html是從for循環加載的,therefire在添加到html後無法運行 –

回答

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>'; 
    } 

而不是使用的顯示/隱藏它更容易從字面上顯示或隱藏。

不知道我是否很好地解釋了這個問題,或者道歉,但感謝一堆答案。

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>'; 
+3

@DarrenSweeney根據你的代碼示例,他們都使用ID = image.article_id – Blazemonger

+0

實際上,在你的例子中你正在做重複的ID。這不是你在這個問題上問你的問題,但它是錯誤的。 – pseudosavant

2

是否將html添加到DOM的任何位置?

如果沒有,試試這個:

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