gpt4 book ai didi

javascript - 更改标签以匹配 ID 中的数字部分

转载 作者:行者123 更新时间:2023-11-28 18:41:21 26 4
gpt4 key购买 nike

我有这个 HTML 代码:

<div id="wrapper">
<div class="row">
<label for="additional_1">Additional #1 :</label>
<input type="text" id="additional_1" name="pnr_remarks_modify[additional][]">
<a href="#" class="addInput">New</a> - <a href="#" class="removeInput">Remove</a>
</div>
</div>

我正在使用以下代码添加(克隆)/删除完整的“.row”元素:

var cloneCntr = 2;
$('#wrapper').on('click', '.addInput', function() {
// clone the div
var row = $(".row").last();
var clone = row.clone();

// change all id and name values to a new unique value
$("*", clone).add(clone).each(function() {
if (this.id) {
this.id = (this.id).slice(0, -1) + cloneCntr;
}
if (this.name) {
this.name = this.name;
}
});
++cloneCntr;
$('#wrapper').append(clone);
});

$('#wrapper').on('click', '.removeInput', function(e) {
e.preventDefault();
var target = $(e.currentTarget);
target.parent().remove();
})

每次我点击New时,我都会从前一个对象中获得一个克隆,但更改了它的ID。例如:

首先点击“新建”

附加#1: 新建 - 删除

第二次单击“新建”

附加#1: 新建 - 删除

但是正如您所看到的,for 属性和标签文本保持不变。我需要将它们更改为(在每个新克隆上):

  • for 需要与新 ID 相同
  • 标签文本需要是Additional # + cloneCntr

但是我不知道如何实现这部分,我可以获得一些帮助吗?

Here is我正在玩的 jsFiddle

最佳答案

每次添加或删除行时,您都可以循环遍历所有行,并根据行索引进行更新。使用在两个事件处理程序中调用的一个函数

$('#wrapper').on('click', '.addInput', function() {
var clone = $(".row").last().clone();
clone.find('input').val(''); // clear value on clone input
$('#wrapper').append(clone);
updateCounts();
});

$('#wrapper').on('click', '.removeInput', function(e) {
e.preventDefault();
var target = $(e.currentTarget);
target.parent().remove();
updateCounts();
});


function updateCounts() {
$('#wrapper .row').each(function(i) {
var num = i + 1,
$row = $(this),
inputId = 'additional_' + num;

$row.find('label').text('Additional #' + num + ' :').attr('for', inputId);
$row.find('input').attr('id', inputId)
});

}

DEMO

关于javascript - 更改标签以匹配 ID 中的数字部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36018419/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com