【问题标题】:jQuery script only executes oncejQuery 脚本只执行一次
【发布时间】:2014-11-01 01:04:11
【问题描述】:

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

【问题讨论】:

  • 你也可以发布相关的 HTML 吗?
  • 按钮是否也被替换了..?第一次点击后控制台是否有任何错误..?
  • 你的新按钮是响应的一部分还是目标 div 的子元素?
  • 你怎么知道它没有执行两次?您是否看到错误,或者什么也没发生?您是否尝试过调试到控制台以查看失败的地方?

标签: javascript jquery html


【解决方案1】:

假设.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
    });
});

【讨论】:

  • 该死...你打败了我 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-16
  • 2014-06-01
  • 2022-01-07
相关资源
最近更新 更多