堆棧再次親愛的朋友...jQuery/PHP喜歡/不像按鈕
我想創建一個簡單的/不像按鈕更新數據庫。 jQuery代碼位於外部文件中。 PHP變量由Codeigniter中的控制器發送。
當頁面加載新鮮時,它會正確顯示當前登錄的用戶是否可以喜歡或不同於他們正在查看的用戶。如果他們點擊一次,一切都按原樣進行 - 按鈕在Like/like之間變化,喜歡的數量增加或減少,數據庫更新。再次點擊時,它會重新加載整個頁面,但不會更新數據庫 - 如何停止刷新並在沒有頁面重新加載的情況下更新?
的PHP:
<div id="like_button">
<p><a href=""><span id="like_unlike" class="link"><?php if($already_liked){echo "Unlike";}else{echo"Like";}?></span></a> (<span id="number_of_likes"><?php echo $number_of_likes; ?></span>)</p>
<span id="liked_unliked_user_id" style="display:none"><?php echo $liked_unliked_user_id; ?></span>
<span id="liking_unliking_user_id" style="display:none"><?php echo $liking_unliking_user_id; ?></span>
</div>
jQuery的:
$(function() {
$('#like_button a').click(function(e) {
var thisrecord = $(this).closest("div");
var liking_unliking_user_id = parseInt(thisrecord.find("span#liking_unliking_user_id").html());
var liked_unliked_user_id = parseInt(thisrecord.find("span#liked_unliked_user_id").html());
var like_unlike = thisrecord.find("#like_unlike").html();
if (like_unlike == 'Like')
{
$(this).replaceWith('<a href=""><span id="like_unlike" class="link">Unlike</span></a>');
var likes = parseInt(thisrecord.find("span#number_of_likes").html()) + 1;
thisrecord.find("span#number_of_likes").html(likes);
$.post(base_url+"/controller/function/" + liked_unliked_user_id + "/" + liking_unliking_user_id);
}
else
{
$(this).replaceWith('<a href=""><span id="like_unlike" class="link">Like</span></a>');
var likes = parseInt(thisrecord.find("span#number_of_likes").html()) - 1;
thisrecord.find("span#number_of_likes").html(likes);
$.post(base_url+"/controller/function/" + liked_unliked_user_id + "/" + liking_unliking_user_id);
}
e.preventDefault();
});
});
感謝這麼多的偉大工程! – whispersan 2013-02-08 22:30:11
沒問題:)。我很多次犯了這個錯誤,很困惑。無論何時您使用注入html的方法 - 新元素都不會附加任何事件。與css不同,將事件應用於jQuery選擇器只會影響在調用jQuery選擇器時存在的元素*。 – 2013-02-08 22:37:38