简体   繁体   中英

Jquery bind doesnt work on AJAX loaded content

I have this script which basically shows the data of the selected row of the table in common text box or in div. the script works perfectly fine with when the page load first time, but i can't get it going on the ajax loaded content. I checked couple of thread on the forum about using .delegate or .on. I can use them with click, mouseenter, mouseleave, but its not working with bind... i tried replacing "tr.bind" with "$(document).delegate($('#Student_List').find('tr'),'click', function(event)" but no luck ... :-(( please help.

I am laoding Ajax Content in division with id StudentDetails.

Thanks in advance.

<script type=Javascript/text>    
$(function() {

    var tr = $('#Student_List').find('tr');
    //$(document).delegate($('#Student_List').find('tr'),'click', function(event) {
    tr.bind('click', function(event) {

        tr.removeClass('row-highlight');
        var tds = $(this).addClass('row-highlight').find('td');

        var studentId = document.getElementById("STUDENT_ID");
        studentId.innerHTML = $(this).children("td:nth-child(1)").text();

        var sName = document.getElementById("STUDENT_NAME");
        sName.innerHTML = $.trim($(this).children("td:nth-child(2)").text());

        $("#STUDENT_PROJECTS").val($.trim($(this).children("td:nth-child(3)").text()));         

    });
});
</script>

<body>
    <div id="StudentDetails">
        <span>Student ID:</span><span id="STUDENT_ID"></span>
        <br/>
        <span>Student Name:</span><span id="STUDENT_NAME"></span>
        <br/>
        <input type="text" name="STUDENT_PROJECTS" id="STUDENT_PROJECTS"/>
        <br/>
        <table id="Student_List">
            <tr><td>1</td><td>James</td><td>Project 1</td></tr>
            <tr><td>2</td><td>Maria</td><td>Project 2</td></tr>
            <tr><td>3</td><td>Frank</td><td>Project 3</td></tr>
        </table>
    </div>
</body>

As others have pointed out in the comments, you need to use a delegate on a non-dynamic parent:

$(function() {

    $('#StudentDetails').on('click', '#Student_List tr', function(event) {

        $('#Student_List tr').removeClass('row-highlight');
        var tds = $(this).addClass('row-highlight').find('td');

        var studentId = document.getElementById("STUDENT_ID");
        studentId.innerHTML = $(this).children("td:nth-child(1)").text();

        var sName = document.getElementById("STUDENT_NAME");
        sName.innerHTML = $.trim($(this).children("td:nth-child(2)").text());

        $("#STUDENT_PROJECTS").val($.trim($(this).children("td:nth-child(3)").text()));         

    });
});

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