在jQuery克隆中替换克隆属性?

时间:2014-01-06 03:50:49

标签: jquery clone

所以我有一个列表,我想克隆并添加新条目:

<li class="splashEntry" data-counter="0">
    <select name="options[0][type]" class="textCtrl">...</select>
    <select name="options[0][sort]" class="textCtrl">...</select>
</li>

我正在使用$('li.splashEntry').last().clone()关闭该字段,并使用.data('counter')获取计数器值。

我现在的问题是,更新数据计数器字段的最佳方法是什么,以及后续创建的克隆中的选择名称?理想情况下,克隆的列表项应具有递增的数据计数器和选择名称。因此克隆的字段将附加到结尾:

<li class="splashEntry" data-counter="1">
    <select name="options[1][type]" class="textCtrl">...</select>
    <select name="options[1][sort]" class="textCtrl">...</select>
</li>

然后,因为这个新条目被附加到结尾;如果我单击按钮创建另一个克隆,它应该将新数据计数器读为1(而不是第一行为0),然后创建一个新的列表项,其中所有条目都表示{{1} }。

实现这一目标的最佳方式是什么?

1 个答案:

答案 0 :(得分:1)

尝试类似

的内容
//cloned element
var $clone = $('li.splashEntry').last().clone(),
    //find the new counter value using old one
    counter = $clone.data('counter') + 1;
//update the data-counter attibute - used attribute instead of data because it gives a visual update on the dom
$clone.attr('data-counter', counter);
//update the name values
$clone.find('[name]').attr('name', function (_, name) {
    return name.replace(/\[\d+\]/, '[' + counter + ']')

演示:Fiddle

相关问题