【问题标题】:Javascript event will not fire up after Ajax callAjax 调用后 Javascript 事件不会触发
【发布时间】:2017-11-14 14:00:55
【问题描述】:

我有一个表单(输入、文本区域和提交按钮),还有一个项目列表。我写了以下脚本:

  1. 当我单击列表项时,textarea 将显示列表项文本内容
  2. 提交时,ajax 调用将 POST 表单而不刷新页面

代码第一次运行良好,但当我点击列表项时将无法更新文本区域(上面的第 1 点将不再起作用)。

var ul = document.getElementById('messages-list');

var listItems = Array.prototype.slice.call(ul.querySelectorAll("li"));

listItems.forEach(function (item) {
  item.addEventListener("click", function (event) {
    document.getElementById("message").textContent = this.textContent;
  });
});

$(function () {

  $('form').on('submit', function (e) {

    e.preventDefault();

    $.ajax({
      type: 'post',
      url: 'send_sms.php',
      data: $('form').serialize(),
      success: function () {
        alert('msg sent');
        $('textarea').val("");
        $('#phoneNumber1').val("");
      }
    });

  });

});

你能帮我解决这个问题吗?提前致谢。

【问题讨论】:

  • 您检查浏览器控制台是否有错误?
  • 我在提交表单后得到这个:[Violation] 'DOMContentLoaded' 处理程序耗时 164ms jquery.min.js:4 [Violation] 'load' 处理程序耗时 902ms
  • 你为什么不使用jQuery来绑定点击处理程序? $("#message-list li").click(function () { $("#message").text($(this).text()); })
  • @SalehMosleh 获取最新信息。 .live() 在 jQuery 1.6 中被弃用并在 1.9 中被删除。
  • @SalehMosleh 不,应该是$("static-selector").on("click", "dynamic-selector", function() {...})

标签: javascript jquery html ajax


【解决方案1】:

在更新 textarea 时尝试更新您的 forEach 以使用 .val()

listItems.forEach(function (item) {
  item.addEventListener("click", function (event) {
    $('#message').val(this.textContent);
  });
});

正如其他人所说,.val() 是获取/设置内容的首选方法 - 将其与 textContent 混合似乎会导致您遇到问题。

【讨论】:

  • 我发现Microsoft Edge中不存在该问题。仅在 Firefox 和 Chrome 中!!!! @柯南
  • @Ray 尝试使用 $(this).text() 而不是 this.textContent。看看有用吗?
  • @Ray (last try) ,尝试将代码放入 $( window ).load(function() { })
  • 实际上,这解决了问题。非常感谢@Canon
猜你喜欢
  • 2012-11-25
  • 1970-01-01
  • 1970-01-01
  • 2013-06-19
  • 1970-01-01
  • 2020-01-26
  • 2014-09-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多