简体   繁体   中英

On Click event not working after loading element through Ajax call

I am loading the page (contains the javascript), and then I am loading the PartialView (contains the table). The problem is, I can't select the table id or the onClick event does not fire.

Index.cshtml

$('#sortingRow').on('click', 'th a', function () {
    $.ajax({
        url: this.href,
        type: 'GET',
        data: { sortOrder: sortOrder },
        success: function (result) {
            $('#sortingRow').parent().html(result);
            LoadSampleDesign();
        }
    });
    return false;
});

_PartialView.cshtml

<table>
    <tr id="sortingRow">
        <th>
            <a href="link">Click Me</a>
        </th>
    </tr>
</table>

That partialView is being loaded using Ajax, like this:

$(sections).on('click', '#sectionPageLinks a', function () {
    $.ajax({
        url: this.href,
        type: 'GET',
        success: function (result) {
            $('#sectionPageLinks').parent().html(result);
            LoadSampleDesign();
        }
    });
    return false;
});

I've tried JsFiddle and the javascript seems to be working correctly. Also, At first, you might think the problem is that jquery couldn't find the table since it was being loaded after DOM completed, but that's why I'm using "on()", doesn't that make it live so it should be able to find the #table even after DOM was completed.

After loading the partial view via Ajax the click event is no longer bound. Change your row click event as follows.

$('#sortingRow').on('click', 'th a', function () {

$(document).on('click', '#sortingRow th a', function () {

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