jQuery - 保持计数并更新动态添加/删除元素的ID

时间:2016-07-04 15:55:53

标签: javascript jquery

我想要做的是当我删除计数中间的元素时,它会更新并保留id的计数,以便它不会跳过编号的id。

我正在做一个表单构建器或自定义表单,它会添加一个无限制的无线电组。

$(document).ready(function () {

    var counter = 1;
    $("#addButton").click(function () {

        var newTextBoxDiv = $(document.createElement('div'))
            .attr("id", 'KpiDiv' + counter);
        newTextBoxDiv.append(
            '<div id="radio">'
        '<label>Performance Criteria #' + counter + ': </label>' +
        '<input type="textbox"' +
        ' id="RadioLabel" value="" name=' + counter + ' ><p></p>' +
        '<label for="radios">Score</label>' +
        '<label class="radio-inline" for="radios-0">' +
        '<input type = "radio" name = "radios" id = "kpi' + counter + '-radios-0" value = "1" checked = "checked" > 1' +
        '</label>' +
        '<label class="radio-inline" for="radios-0">' +
        '<input type = "radio" name = "radios" id = "kpi' + counter + '-radios-0" value = "2" checked = "checked" > 2' +
        '</label>' +
        '<label class="radio-inline" for="radios-0">' +
        '<input type = "radio" name = "radios" id = "kpi' + counter + '-radios-0" value = "3" checked = "checked" > 3' +
        '</label>' +
        '<label class="radio-inline" for="radios-0">' +
        '<input type = "radio" name = "radios" id = "kpi' + counter + '-radios-0" value = "4" checked = "checked" > 4' +
        '</label>' +
        '<label class="radio-inline" for="radios-0">' +
        '<input type = "radio" name = "radios" id = "kpi' + counter + '-radios-0" value = "5" checked = "checked" > 5' +
        '</label>' +
        '</div>'
        );
        newTextBoxDiv.appendTo("#FormGroup");
        counter++;
    });

    $("#removeButton").click(function () {
        if (counter == 1) {
            alert("Nothing more to remove");
            return false;
        }

        counter--;
        $("#RadioBoxDiv" + counter).remove();
    });

0 个答案:

没有答案