Home>

There is the following code:

$(document).ready(function(){
    $('.table tr').hover(function(){
        $(this).addClass('hover');
    }, function() {
        $(this).removeClass('hover');
    });
    $('.table tr').click(function(){
        $('.table tr').removeClass('active');
        $(this).addClass('active');
    $fordel=$(this).children('td:last-child').text();
    $fordell=$(this).children('td:first-child').text();
    alert($fordel);
    });
});
function Geeks() {
row= $("<tr id='5'></tr>");
                col1= $("<td>5</td>");
                row.append(col1).prependTo("#myTable");
               }
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script><table id="myTable" class="table">  <tr id="1"><td>1</td></tr>  <tr id="2"><td>2</td></tr>  <tr id="3"><td>3</td></tr>  <tr id="4"><td>4</td></tr></table><a class="delete" href="#" onclick='Geeks()'>Add</a>          

By clicking on the initial rows of the table, we get the text from the cell into the alert. However, the script does not work for the newly added row. How to fix?

  • Answer # 1

    Write handlers via delegation:

    $(document).on('hover', '.table tr', function()
    

    And

    $(document).on('click', '.table tr', function()
    

    Iftableis never added dynamically, then instead ofdocumentyou can write it, and then in the selector further write onlytr

    Everything worked out, only the style for hover disappeared for some reason, the style is applied for the pressed one.

    JavaQuest2022-02-12 23:15:12

    Yes, because this is no longer the method itself, but the delegation of the event, then you need to rewrite it a little differently. I would use mouseenter and mouseleave

    Алексей Шиманский2022-02-12 23:15:12