2014-10-31 357 views
0

在我的網站上,我有一個jQuery腳本,當點擊一個按鈕時,用另一個文件中的HTML代替div的內容。每個按鈕的ID都與在div中替換的HTML文檔的文件名相同。jQuery腳本只執行一次

在主頁上單擊所有按鈕並且內容被替換時,所有按鈕都會起作用。但是,當我嘗試點擊其中一個新按鈕來替換內容時,沒有任何反應。任何想法爲什麼它不會執行兩次?

// JavaScript Document 
$(document).ready(function() { 
    $('.button').click(function(e) { 
    e.preventDefault(); // Stops the browser from following the href in the <a> 
    var that = $(this) 
     , id = that.attr('id') 
     , url = 'questions/' + id + '.html' 
     ; 
    $.post(url, function(data) { 
     $('#replace').html(data); // Display external file to target div 
     window.scrollTo(0, 0);  // Forces a scroll back to the top of the page 
    }); 
}); 
}); 
+1

您是否也可以發佈關聯的HTML? – 2014-10-31 16:59:03

+0

該按鈕是否也被取代..?第一次點擊後,控制檯中是否有任何錯誤? – 2014-10-31 17:01:08

+0

你的新按鈕是目標div的響應和孩子的一部分嗎? – lshettyl 2014-10-31 17:01:23

回答

2

假設.button元素是被替換的HTML的一部分,新元素將不會附加處理程序。您需要將您的處理程序附加到身體上,而不是由button類別過濾:

$(document).on('click', '.button', function(e) { 
    e.preventDefault(); // Stops the browser from following the href in the <a> 
    var that = $(this) 
     , id = that.attr('id') 
     , url = 'questions/' + id + '.html' 
     ; 
    $.post(url, function(data) { 
     $('#replace').html(data); // Display external file to target div 
     window.scrollTo(0, 0);  // Forces a scroll back to the top of the page 
    }); 
}); 
+0

補...你打我吧:) – 2014-10-31 17:04:38

+0

真棒謝謝你! – 2014-10-31 18:22:05