2014-01-07 105 views
3

我有了這個功能後才能正常運行:jQuery函數不Ajax調用

$(document).ready(function() { 
$('.post_button, .btn_favorite').click(function() { 


//Fade in the Popup 
$('.login_modal_message').fadeIn(500); 

// Add the mask to body 
$('body').append('<div class="overlay"></div>'); 
$('.overlay').fadeIn(300); 
return false; 
}); 

我的頁面加載內容與收藏夾按鈕,但Ajax調用和產生額外的新內容之後,該功能不工作時您點擊新內容的按鈕。有什麼不對的?

+0

而在你的HTML和Ajax調用後問題。 – Khamidulla

回答

10

那是因爲您正在使用動態內容。

您需要將您的點擊通話更改爲委託的方法類似on

$('.post_button, .btn_favorite').on('click', function() { 

$("body").on("click", ".post_button, .btn_favorite", function(event) { 
+0

如果我錯了,請更正,但.on方法仍然可用? –

+0

是的,它是可用的。 –

+0

嗯所以爲什麼我會在FireBug中得到「TypeError:$(...)。on不是函數」? –

0

我不知道如果我得到你的問題的權利,但你可能想嘗試。 。

$.ajax({ 
    url: "test.html" 
}).done(function() { 
    $('.post_button, .btn_favorite').click(function() { 


    //Fade in the Popup 
    $('.login_modal_message').fadeIn(500); 

    // Add the mask to body 
    $('body').append('<div class="overlay"></div>'); 
    $('.overlay').fadeIn(300); 
    return false; 
}); 

試着將你的代碼粘貼到done功能。

希望它能幫助:)

編輯: 我也注意到你缺少你的問題});

+0

嗨,超出範圍。但是,謝謝你的努力! –

+0

對不起:),你的意思是在ajax完成後,'click'函數不會執行? – HTTP

3

取而代之的是:

$('.post_button, .btn_favorite').click(function() { 

做到這一點:

$(document).on('click','.post_button, .btn_favorite', function() { 

on將與存在的元素和今後的選擇相匹配的工作。

乾杯

+0

解釋爲什麼使用'on'可以解決問題。使用'$(document)'也是一個改變,爲我解決了同樣的問題。 – GWR

0

如果您知道.post_button的容器,btn_favorite然後用

$('#container_id').on('click', '.post_button, .btn_favorite', function() { }); 

所以如果'.post_button, .btn_favorite'不那麼發現它會冒泡到container_id

否則,如果你不知道該容器然後委託它來記錄

$(document).on('click', '.post_button, .btn_favorite', function() { }); 

Reference

0

以下爲我工作

$(document).ready(function(){ 
     $(document).bind('contextmenu', function(e) { 
      if(e.button == 2 && jQuery(e.target).is('img')) { 
       alert('These photos are copyrighted by the owner. \nAll rights reserved. \nUnauthorized use prohibited.'); 
       return false; 
      } 
     }); 
    }); 
0

您需要jQuery的單擊事件綁定,一旦你的Ajax內容在AJAX成功塊替換舊的內容

你需要喜歡這裏新的響應HTML內容的一個代碼添加標籤就像

<a href="#" id="new-tag">Click Me</a> 

所以,你可以綁定新的單擊事件改變內容與下面的代碼

$("#new-tag").click(function(){ 
    alert("hi"); 
    return false; 
});