表格不是通过 PHP 排序而是在 HTML 中排序

我有一个由 php 创建的 html 表,我想对这个表进行排序,但没有成功。如果我在 html 中创建表格,则排序工作。


<!DOCTYPE html>

<html>

<head>

<title>Teste</title>

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

<link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css">

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>

<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>

<script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>

</head>

<body>

 <div class="container mb-3 mt-3" id="inicio">

 </div>



<script>

$(document).ready(function(){

load_list();

$('.mydatatable').DataTable();

function load_list()

{

    var action = "data";

    $.ajax({

        url: "teste.php",

        method:"POST",

        data:{action:action},

        success:function(data)

        {

            $('#inicio').html(data);

        }

    })

}


}); 

</script>

</body>

</html>

我认为 $('.mydatatable').DataTable(); 是在错误的地方,我尝试了我的选择,但只有在表格位于 html 页面内时才有效。任何人都可以帮助我吗?


qq_花开花谢_0
浏览 129回答 2
2回答

aluckdog

作为第一个 A in ajaxmean asynchronous,然后您的调用$('.mydatatable').DataTable();发生在通过 ajax 加载实际数据之前。您应该将呼叫移动DataTable到success回调:success:function(data){&nbsp; &nbsp; // note the order - first you load `html`&nbsp; &nbsp; $('#inicio').html(data);&nbsp; &nbsp; // after that you have a `.mydatatable` selector available&nbsp; &nbsp; $('.mydatatable').DataTable();}

慕妹3146593

初始化数据表时,表格 html 不存在。$(document).ready(function(){load_list();function load_list(){&nbsp; &nbsp; var action = "data";&nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; url: "teste.php",&nbsp; &nbsp; &nbsp; &nbsp; method:"POST",&nbsp; &nbsp; &nbsp; &nbsp; data:{action:action},&nbsp; &nbsp; &nbsp; &nbsp; success:function(data)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $('#inicio').html(data);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //move this to here&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $('.mydatatable').DataTable();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; })}
打开App,查看更多内容
随时随地看视频慕课网APP