开发者

jquery add/delete html row

i have a simple html table where i want to delete and add rows dynamically. the html table has a delete icon, by clicking on it a jquery script deletes the row.

code for the table:

<table id="table1"><tr><td>
<img class="delete" alt="delete" src="delete_icon.png" />
</td></tr></table>

a link adds a new row:

<a href="#" name="addRow">Add Row</a>

both jquery scripts above the html table code:

<script type="text/javascript">
    /* delete row */
    $(document).ready(function () {
        $('#table1 td img.delete').click(function () {
            $(this).parent().parent().remove()开发者_运维问答;
        });
    });

    /* add new row */
    $(document).ready(function () {
        // Code between here will only run when the document is ready
        $("a[name=addRow]").click(function () {
            // Code between here will only run when the a link is clicked and has a name of addRow
            $("table#table1 tr:last").after('<tr><td><img class="delete" alt="delete" src="@Url.Content("~/content/delete_icon.png")" /></td></tr>');
            return false;
        });
    });

</script>

the problem is the following: both delete and insert operations work. however when i add a new row and try to delete this row, nothing happens. i can only delete already existing rows, the jquery script doesn't work on newly added rows.

any ideas?


You need to use live()

$('#table1 td img.delete').live('click', function(){ ... });
$("a[name=addRow]").live('click', function (){ ... }); 


$('#table1 td img.delete').click(function () {

only binds the click handler to elements that are already present. You either have to bind this handler to the newly added rows at the moment you add them, or use event delegation via .delegate or .live.


That's because the newly added rows don't have the click event handler attached to the delete link. You'll have to manually add it when creating the new row or use live() which will automatically attach events to newly created DOM nodes.


You need to use the jQuery live function that allows you to bind events to elements that have not yet been introduced to the DOM.

$(document).ready(function() {
    $('#table1 td .delete').live('click', function() {
        $(this).parent().parent().remove();
    });
});

I have added an example here on jsFiddle but had to swap your img tags for a tags not have access to your image.


The new elements are not getting the click handler attached. You can re-attach it every time you add a row by executing the same code to initialize but during click event.

See jsfiddle here: http://jsfiddle.net/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜