javascript - 如何在ajax之外访问dataTable变量

标签 javascript jquery ajax datatables

我有一个在函数调用内创建的数据表。但是如果我想基于 event listeners like this 创建新行,它给出了表变量未定义的错误,这是可以理解的,因为它是在函数调用内部而不是全局的。那么,如何为此创建解决方法并在 $(document).ready() 部分下添加事件监听器?

我的 JS 文件的结构非常简陋,但它就是这样的。

$(document).ready(function()
{
     var table=null;
     $('#button').click(function()
     {
         callfunction1();
     }
     callfunction1()
     {
         $.ajax({
              'success': function(response) //response contains the plain table
                         {
                             createDatatable(response)
                         }
         })
     }
     createDatatable(response)
     {
            $('#division').html(response); //creating the plain table
            table=$('#tableId').Datatable({}); //converting it to datatable
     }
     //I want to add event listeners here, because if I add
     //it anywhere else, it doesn't work, because basically
     //it's a function call.
}

最佳答案

您可以在更广泛的范围内创建table var的实例,例如:

//the table is now a window object variable window.table
var table = null;
$(document).ready(function()
{
     $('#button').click(function()
     {
         callfunction1();
     }
     callfunction1()
     {
         $.ajax({
              'success': createDatatable()
         })
     }
     createDatatable()
     {
            table=$('#tableId').Datatable({})
     }

     //the table is binded in the window scope so you can use in your event listeners
}

关于javascript - 如何在ajax之外访问dataTable变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47328533/

相关文章:

javascript - jQuery 滚动时折叠

javascript - 如果使用严格 DI,如何从 jQuery 调用 Controller 函数

javascript - 在 WordPress 中单击“发布”时发送 Ajax

asp.net - 如何使用ajax调用跨域Web API?

javascript - 禁用键盘快捷键

javascript - 无法创建 SSL/TLS 安全通道

javascript - Alexa Node js Lambda 函数给出响应 null

javascript - 大视频 : How to Hide Control Options Under Video

php - 使用 Javascript 编辑和保存用户 HTML - 它有多安全?

javascript - 表单提交为空