简体   繁体   English

Ajax调用后,Javascript事件不会触发

[英]Javascript event will not fire up after Ajax call

I have a form (input, textarea and submit button) and I also have a list of items. 我有一个表格(输入,文本区域和提交按钮),我也有一个项目列表。 I wrote the following script to: 我将以下脚本编写为:

  1. when I click a list item the textarea will show the list item text content 当我点击列表项的文本区域将显示列表项的文本内容
  2. on submit, ajax call will POST the form without refreshing the page 在提交时,ajax调用将在不刷新页面的情况下发布表单

the code works fine in the first time but then I will not be able to update the textarea when I click on a list item anymore (point #1 above will not work again). 该代码在第一次可以正常工作,但是当我单击列表项时,我将无法更新textarea(上面的#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("");
      }
    });

  });

});

Can you please help me fix this issue? 你可以帮我解决这个问题? Thanks in advance. 提前致谢。

Try updating your forEach to use .val() when updating the textarea : 尝试在更新textarea时更新forEach以使用.val()

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

As stated by others, .val() is the preferred method of getting / setting content - mixing this with textContent appears to cause the issue you're experiencing. 如其他人所述, .val()是获取/设置内容的首选方法-将其与textContent混合似乎会导致您遇到问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM