克隆项目时,是否可以更改所有输入属性和 ID,如下所示;

When cloning an item, is it possible to change ALL the inputs attributes and IDs as this;

本文关键字:输入 ID 属性 项目 是否      更新时间:2023-09-26

代码笔链接以查看实际操作

假设我有这个标记:

<div class="wrapper-1">
  <input id="name-1" class="name-input" type="text" name="name"/>
  <input id="surname-1" type="text" name="surnamename"/>
  <input id="telephone-1" type="text" name="telephone"/>
  <input id="email-1" type="text" name="email"/>
  <input id="comments-1" type="text" name="comments"/>
</div>
<button>Clone me</button>

而这个JavaScript来处理克隆

$('button').click(function() {
  var d = $('div');
  var counter = d.length;
  var newCounter = new Number(counter + 1);
  var cloned = $('.wrapper-' + counter).clone().attr('class', 'wrapper-' + newCounter).fadeIn('slow');
  //Finding items that need to have different ID
  cloned.find('.name-input').attr('id', '#name-' + newCounter);
  //Cloning
  $('.wrapper-' + counter).after(cloned);
});

如您所见,带有类.name-input的输入的 ID 计数器会随着包装器的计数器而变化。

但是,如果我想更改它的名称,以及 4 个较低输入的所有 ID 和名称,我必须手动插入和复制相同的代码:

cloned.find('.name-input').attr('id', '#name-' + newCounter);

想象一下,我有25个。

所以我的问题是:

是否可以插入这样的东西:

cloned.find('input').attr('id', $(this).attr('id') + '-' + newCounter);

我的意思是浏览器会自动解析元素的名称和 ID,并将 counter 变量添加到其中。

当然,在这个给定的示例中,$(this)将引用触发事件的元素 - button ,但也许这种方法是可能的?

这就是 jQuery each() 函数所做的,例如:

var buttonId = $(this).attr('id');
cloned.find('input').each(function() {
    $(this).attr('id', buttonId + '-' + newCounter);
});

each()函数中的代码是为集合中的每个元素执行的。在此函数中,this 是指当前应用代码的元素。

还有其他jQuery函数的工作方式类似,例如filter()