在克隆div div中的最后一个div之前,我需要更新name属性,以便我不会以重复的名字结束。我该怎么做?我尽可能多地做了,但一度堆叠。我现在的JQ可能看起来很傻,如果你提供更好的JQ,我很乐意改变它,因为我是JQ的新人。
由于
HTML
<div id="label-field-cover">
<div><input type="text" value="" name="size-label-1"></input></div>
<div><input type="text" value="" name="size-label-2"></input></div>
<div><input type="text" value="" name="size-label-3"></input></div>
</div>
JQ
//Clone last div
var $cloned = $('#label-field-cover div:last').clone();
//Get the content of cloned div
var clonedContent = $cloned.html();
//This echos: ""<input name="size-label-3" value="" type="text">""
console.log(clonedContent);
//I need to change name="size-label-3" to name="size-label-4" somewhere here first
//This adds cloned element after last div
$('#label-field-cover div:last').after($cloned);
答案 0 :(得分:3)
我认为你应该使用last()方法而不是div:last因为this。 类似的东西:
var $cloned = $('#label-field-cover div').last().clone();
使用jQuery,您想要实现的目标很简单:
var new_name = $cloned.children('input').attr('name', 'size-label-4');
jQuery很棒,所以你可以这样做:
$cloned.children('input').attr('name', 'size-label-4');
$('#label-field-cover div').last().after($cloned);
我希望它有效,我没有测试它xD
答案 1 :(得分:1)
由于您要追加一个新元素,因此调用last将选择该元素,您可以使用属性标记对其进行重命名
//Clone last div
var $cloned = $('#label-field-cover div:last').clone();
//Get the content of cloned div
var clonedContent = $cloned.html();
//This echos: ""<input name="size-label-3" value="" type="text">""
console.log(clonedContent);
//I need to change name="size-label-3" to name="size-label-4" somewhere here first
//This adds cloned element after last div
$('#label-field-cover div:last').after($cloned);
//Add this in
$('#label-field-cover div:last input').attr("name", "size-label-4");
在此处添加$('#label-field-cover div:last input')
输入值会使其定位label-field-cover对象中最后一个div元素的子输入元素
答案 2 :(得分:0)
你去:http://jsfiddle.net/vimes1984/4aXdV/22/
//Clone last div
var $cloned = $('#label-field-cover div:last').clone();
//Get the content of cloned div
var clonedContent = $cloned.html();
//This adds cloned element after last div
$('#label-field-cover div:last').after($cloned);
//first we get the newly added attribute name
var clonedattr = $('#label-field-cover div input:last').attr('name');
//regex to match the diigits in it
var clonednumber = clonedattr.match('([0-9]|[1-9][0-9]|[1-9][0-9][0-9])');
//first digit returned we change from string to a actual number
var getnumber = parseInt(clonednumber[0]);
//add one to it
var addone = getnumber += 1;
//check to make sure it's actually added
console.log(addone);
//reapply to the last INPUT the attribute with the added number...
$('#label-field-cover div:last input').attr('name', 'size-label-' + addone);
这将对最后添加的输入进行渐变并将值加1,然后将名称更改为新的添加值