在我的网站上,我有一个jQuery脚本,当单击按钮时,该脚本将div的内容替换为另一个文件中的HTML。每个按钮的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
    });
});

09-25 16:57
查看更多