[英]jQuery script only executes once
在我的網站上,我有一個jQuery腳本,當單擊按鈕時,該腳本會用另一個文件中的HTML替換div的內容。 每個按鈕的ID均與在div中替換的HTML文檔的文件名相同。
單擊主頁上的所有按鈕后,所有按鈕都會起作用,並且內容將被替換。 但是,當我嘗試單擊新按鈕之一來再次替換內容時,什么也沒有發生。 知道為什么它不會執行兩次嗎?
// 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
});
});
});
假設.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
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.