javascript - 克隆表行

标签 javascript jquery

我有下表

<table id="customFields" class="table table-bordered table-hover additionalMargin alignment">
    <thead>
    <tr>
        <th colspan="2"></th>
        <th>Some Title</th>
    </tr>
    </thead>
    <tbody>
        <tr>
            <td><label class="subjectline" for="User1">User NOC M1</label></td>
            <td id="slLabel">SLA</td>
            <td id="slInput"><input type="text" name="slOptions[User][NOC M1]" class="form-control" id="User1"></td>
            <td><a class="addCF" href="javascript:void(0);">+ additional user</a></td>
        </tr> 
    </tbody>
</table>

然后我有以下 javascript 来添加额外的行

$(function() {
    $(".addCF").click(function(){
        $("#customFields").append('<tr><td></td><td>SL_B</td> <td><input type="text" name="slOptions[User][NOC M1]" class="form-control" id="User1"></td> <td> &nbsp; <a href="javascript:void(0);" class="remCF">Remove</a></td></tr>');
    });
    $("#customFields").on('click','.remCF',function(){
        $(this).parent().parent().remove();
    });
});

这目前按我希望的方式工作。但是,有几件事我遇到了问题。

首先,当您第一次查看它时,您会看到标签 SL_A。在克隆版本中,我手动将其设置为 SL_B。然后所有其他克隆都具有 SL_B。我想要做的是让 SL_ 后跟字母表中的下一个字母。所以第三行应该是SL_C。我不太确定如何实现这一目标。

我的第二个问题与克隆输入的名称有关。目前,它们都具有相同的名称,例如slOptions[用户][NOC M1] 添加新行时,名称应更改为唯一的名称,可能使用上面字母表中的其他字母,例如slOptions[用户][NOC M1B]

是否有可能实现这些事情?

我已经设置了一个 Fiddle用于演示

谢谢

最佳答案

您可以存储对可能字母以及当前字母的引用,然后在您的函数中确定要使用的适当字母:

// Store the possible letters
var possibleLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
// Store the current letter
var currentLetter = 'A';

$(function() {
    $(".addCF").click(function(){
        // Resolve the next letter to add
        var nextIndex = possibleLetters.indexOf(currentLetter) + 1;
        // Update your reference
        currentLetter = possibleLetters[nextIndex];
        // Append it
        $("#customFields").append('<tr><td></td><td>SL_' + currentLetter + '</td> <td><input type="text" name="slOptions[User][NOC M1' + currentLetter + ']"...');
        // More code omitted for brevity
    });
    // Still more code omitted for brevity
});

您可以 see an example of this in action here并在下面演示:

enter image description here

关于javascript - 克隆表行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36866289/

相关文章:

javascript - 如何通过nlapi方法在saveRecord函数中保存多条记录?

javascript - 在多重选择器中使用变量

javascript - 仅在鼠标悬停时更改图片一次

jquery - fancybox 2 画廊的幻灯片,包含图像和视频,但等待视频完成

javascript - 未为我的简单按钮show-div javascript定义的功能

javascript - 从 vue 指令操作目标的 dom

javascript - 是什么导致某些页面上的 jQuery "$(...) is null"?

javascript - 使用 UIWebView 从本地资源运行 javascript

javascript - 将 jQuery 对象返回到字符串中

jQuery 验证 showerrors 显示名称