Search code examples
jqueryhtml-tablemouseenter

How to append td with last-child jquery?


I created the following code:

<table id="map">
    <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
    </tr>
</table> 

<script>
    $(document).ready(function(){
        $('td:last-child').mouseenter(function(){
            var tdId = $(this).attr('id');
            var newId = parseInt(tdId);
            $(this).after('<td>new</td>');
        });         
    });
</script>

I want to create a new td when the mouse enter on last-child the tds. That code is working. but when I want to create a new td again I must hover on <td>3</td> not on last td that create automatically! How can I fix that?!


Solution

  • Use event delegation instead of binding the handlers directly to the td elements:

    $('#map').on('mouseenter', 'td:last-child', function(){
       // code here
    });
    

    http://jsfiddle.net/DyTpJ/