使用 JQUERY 更改输入名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7118745/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Changing input name using JQUERY
提问by Lidong Ghon
I'm trying to change all the input name based on the list index of <li>
but it seems like it's not changing at all.
我正在尝试根据的列表索引更改所有输入名称,<li>
但似乎根本没有更改。
$('.test').click(function() {
for(var i=0;i<$("li.songs").length;i++)
{
var ob = $("li.songs").eq(i).clone();
ob.find('input').each(function()
{
this.name = this.name+i;
alert(this.name); //just checking if does it change
});
}
});
Now, the alert displays the right name I want, BUT no changes on the name when I inspect the element AND try to submit the form and display all the POST values.
现在,警报显示我想要的正确名称,但是当我检查元素并尝试提交表单并显示所有 POST 值时,名称没有更改。
Example expected output before changing:
更改前的预期输出示例:
<li class="songs"><input type="text" name="song" /></li>
<li class="songs"><input type="text" name="song" /></li>
<li class="songs"><input type="text" name="song" /></li>
After changing:
更改后:
<li class="songs"><input type="text" name="song1" /></li>
<li class="songs"><input type="text" name="song2" /></li>
<li class="songs"><input type="text" name="song3" /></li>
NOTE: I DO NOT WANT the input named song to be an ARRAY.
注意:我不希望名为歌曲的输入是一个数组。
回答by Jens Roland
You are cloning the object, so the change is done to a copy rather than the original DOM node.
您正在克隆对象,因此更改是对副本而不是原始 DOM 节点进行的。
Don't use clone()
and you'll be fine. Or do this:
不要用clone()
,你会没事的。或者这样做:
$("li.songs input").each(function(i) {
$(this).attr('name', $(this).attr('name') + i);
});
回答by Dogbert
$("li.songs").each(function(i) {
$(this).find('input').attr('name', 'song' + i);
});