【问题标题】:EJS Script unable to execute within ajax 'success' callEJS 脚本无法在 ajax“成功”调用中执行
【发布时间】:2016-07-12 10:13:59
【问题描述】:

我有一个使用 AJAX 检索一些数据的 EJS 页面。加载数据后,我想将某些内容附加到 div。在附加的内容中,有使用以下脚本的复选框:

<script>
$('#selectall').change(function () {
    $('.checkbox').prop('checked', this.checked).trigger('change');
});
</script>

这是我的 ajax:

$.ajax({
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json',
url: 'http://localhost:3000/mytableajax',
success: function(result) {
    //result is printed, everything is retrieved correctly
    $('#mytable').empty(); 
    var eventresult = JSON.parse(result);
    var node = document.getElementById('mytable');

    toAppend += '<input type="checkbox" id="selectall" class="c-check">'; //This checkbox will allow me to select all other checkboxes

    //I have other checkboxes appended at the bottom with the class "checkbox"


    node.innerHTML = toAppend;
    document.getElementById('mytable').appendChild(node);
})

当我第一次访问该页面时,全选功能起作用。但是,当使用 AJAX 更改数据时,如上面的代码所示,全选功能停止工作。我认为我的脚本似乎无法在 AJAX 的“成功”回调中执行,因为在使用 AJAX 更改/附加后,我所有使用脚本的函数似乎都失败了。

有没有办法在我的 AJAX“成功”回调中执行脚本?感谢任何反馈/建议!

【问题讨论】:

    标签: javascript jquery ajax


    【解决方案1】:

    我找到了一个真正有效的解决方案,希望它可以帮助遇到同样问题的人。

    $(document).on('change', '#selectall' , function() {
        $(".checkbox").attr('checked', $(this).is(":checked")).trigger('change');
    });
    

    基本上,以这种格式使用 .on 方法而不是 .change 方法允许来自 AJAX 的内容访问此脚本。

    从这里得到想法: https://forum.jquery.com/topic/use-on-click-do-not-work-after-ajax-call

    【讨论】:

      猜你喜欢
      • 2018-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多