我有一个在函数调用内创建的数据表。但是如果我想基于 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/