简体   繁体   中英

jQuery problems with parent().remove()

I am trying to clone and remove a table with jQuery, without success. Here is an example, the table I want to operate:

<table>
    <tr>
        <td colspan="6" class="linha_space"></td>
    </tr>
    <tr>
        <td colspan="3">Dummy1</td>
        <td colspan="3">Dummy2</td>
    </tr>
    <tr>
        <td colspan="2"><input name="aperf_cursos[]" type="text" /></td>
        <td colspan="2"><input name="aperf_entidades[]" type="text" /></td>
        <td colspan="2"><a href="javascript:void(0);" class="adicionar" onclick="add(this);"><img src="./images/add.gif" /></a><a href="javascript:void(0);" class="remover" onclick="remove(this);" style="display: none;"><img src="./images/delete.gif" /></a></td>
    </tr>
    <tr>
        <td colspan="6" class="linha_space"></td>
    </tr>
</table>

Now, the javascript functions add() and remove():

function add(o){
    var o = $(o);
    var tr = o.parent().parent().parent();
    tr.after(tr.clone()); 
    tr.find('.adicionar').remove();
    tr.find('.remover').show();
    tr.next().find('input, select').val('');
    tr.next().find('.remover').hide();
}
function remove(o){
    var o = $(o);
    o.parent().parent().parent().remove(); 
}

add(this) works perfectly, but the remove(this) is not working, it removes just my "delete.gif" image. What am I doing wrong please?

Instead of this parent.parent.parent madness (it's madness, yes it is) why don't you use

element.closest("tr")

to find the row it's in?

This approach will work consistently.

Look at the jsFiddle .

I used jQuery for what you need.

<table>
    <tr>
        <td colspan="6" class="linha_space"></td>
    </tr>
    <tr>
        <td colspan="3">Dummy1</td>
        <td colspan="3">Dummy2</td>
    </tr>
    <tr>
        <td colspan="2"><input name="aperf_cursos[]" type="text" /></td>
        <td colspan="2"><input name="aperf_entidades[]" type="text" /></td>
        <td colspan="2"><a href="#" class="adicionar">Add</a><a href="#" class="remover" style="display: none;">Delete</a></td>
    </tr>
    <tr>
        <td colspan="6" class="linha_space"></td>
    </tr>
</table>

$(function() {
    $(document).on('click', '.adicionar', function(event){
        var o = $(event.target);
        var tr = o.closest('table');
        tr.after(tr.clone()); 
        tr.find('.adicionar').remove();
        tr.find('.remover').show();
        tr.next().find('input, select').val('');
        tr.next().find('.remover').hide();
    });

    $(document).on('click', '.remover', function(event){
        var o = $(event.target);
        var table = $(o.closest('table')); 
        table.remove();        
    });
});

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