jQuery 追加和删除动态表行 [英] jQuery append and remove dynamic table row

查看:26
本文介绍了jQuery 追加和删除动态表行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以为一个表添加多行,但我无法删除很多行.每个顺序添加我只能删除 1 行.

I can add many rows for a table, but I can't remove many rows. I only can remove 1 row per sequential add.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#addCF").click(function(){
        $("#customFields").append('<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td><input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" /> &nbsp; <input type="text" class="code" id="customFieldValue" name="customFieldValue[]" value="" placeholder="Input Value" /> &nbsp; <a href="javascript:void(0);" id="remCF">Remove</a></td></tr>');
        $("#remCF").on('click',function(){
            $(this).parent().parent().remove();
        });
    });
});
</script>

<table class="form-table" id="customFields">
<tr valign="top">
    <th scope="row"><label for="customFieldName">Custom Field</label></th>
    <td>
        <input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" /> &nbsp;
        <input type="text" class="code" id="customFieldValue" name="customFieldValue[]" value="" placeholder="Input Value" /> &nbsp;
        <a href="javascript:void(0);" id="addCF">Add</a>
    </td>
</tr>
</table>

您可以在 http://jsfiddle.net/3AJcj/

我需要帮助.

推荐答案

每页只能有一个唯一 ID.将这些 ID 更改为类,并更改 jQuery 选择器.

You only can have one unique ID per page. Change those IDs to classes, and change the jQuery selectors as well.

另外,将 .on() 移到 .click() 函数之外,因为您只需要设置一次.

Also, move the .on() outside of the .click() function, as you only need to set it once.

http://jsfiddle.net/samliew/3AJcj/2/

$(document).ready(function(){
    $(".addCF").click(function(){
        $("#customFields").append('<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td><input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" /> &nbsp; <input type="text" class="code" id="customFieldValue" name="customFieldValue[]" value="" placeholder="Input Value" /> &nbsp; <a href="javascript:void(0);" class="remCF">Remove</a></td></tr>');
    });
    $("#customFields").on('click','.remCF',function(){
        $(this).parent().parent().remove();
    });
});

这篇关于jQuery 追加和删除动态表行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆