假设我有这个标记:
<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);
});
如您所见,具有 class.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()
。
关于javascript - 克隆项目时,是否可以像这样更改所有输入属性和 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27673420/