简体   繁体   中英

How to apply jQuery databale after refreshing its container div?

I am trying to apply jQuery datatable structure after refreshing it's container div.

I have one div in which I have datatable. For the first visit, it works fine, but on button click event I am refreshing it's parent div. And after that I am expecting datatable structure on table but it's not working.

<div id="students">   
    <table id="studTable" class="table fullwidth data">
        <thead>
            <tr>
                <th> Name</th>
                <th> DOB</th>
                <th> Email</th>
            </tr>
        </thead>
        <tbody>
        @foreach (var stud in Model)
        {
            <tr>
                <td>@stud.Name</td>
                <td>@stud.DOB</td> 
                <td>@stud.Email</td> 
            </tr>
        }
        </tbody>
    </table>
</div>

I am reading data from model in MVC view. For first load it shows jQuery datatable structure. On button click I executes this jQuery code:

<script type="text/javascript">
    $(".submit").click(function (event) {
        $("#students").load(location.href + " #students");
            $("#studTable").dataTable({
                "bSort": false,
                "bPaginate": true,
                "bInfo": true,
                "bFilter": false,
                "bLengthChange": false,
                "pagingType": "simple_numbers",
        });
    })
</script>

This code reloads students div but the datatable is not getting apply. And when I am writing datatable's code inside setTimeout function then it loads jQuery datatable correctly.

setTimeout(function () {          
        }, 1000);

but here I don't want to use this setTimeout(function(){},1000);

Is there any solution for this scenario?

The .load() function is asynchronous, so effectively you're trying to apply the DataTables plugin before the content has finished loading. Instead of applying the plugin on the next line of code, apply it in the asynchronous callback:

$("#students").load(location.href + " #students", function () {
    $("#studTable").dataTable({
        "bSort": false,
        "bPaginate": true,
        "bInfo": true,
        "bFilter": false,
        "bLengthChange": false,
        "pagingType": "simple_numbers",
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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