用jQuery设置新的id [英] Set new id with jQuery
问题描述
this是一个文本字段,new_id是一个整数。
"this" is a text field, "new_id" is an integer.
当我应用以下代码段时:
When I apply the following snippet:
$(this).attr('id', this.id + '_' + new_id);
$(this).attr('name', this.name + '_' + new_id);
$(this).attr('value', 'test');
id改变,名称也改变,但不是值。如果我将最后一行更改为此(因此使用字符串文字)
the id changes, the name changes too, but not the value. If I change the last line to this (and therefore use a string literal)
$('#mytextfield_3').attr('value', 'test');
它有效。
有什么想法吗?
- 编辑 -
感谢Steerpike进行快速插件测试 - 我相信它应该可行,但我找不到错误。
-- EDIT -- Thanks to Steerpike for the quick plugin test - i believe it should work, but i can't find the error.
以下是一些代码:
我使用
clone = $(this).find('.clone_fields_container:first').clone();
clone现在包含一个嵌入了输入字段的div。
"clone" now contains a div which has embedded input fields.
生成新ID后:
/** Iterate over input and select fields in container */
clone.children('input,select,textarea').each(function() {
$(this).attr('id', this.id + '_' + new_id);
$(this).attr('name', this.name + '_' + new_id);
$(this).val('test');
console.log(this);
});
文本字段没有任何值。
推荐答案
我刚刚编写了一个快速插件,使用相同的代码段运行测试,并且工作正常
I just wrote a quick plugin to run a test using your same snippet and it works fine
$.fn.test = function() {
return this.each(function(){
var new_id = 5;
$(this).attr('id', this.id + '_' + new_id);
$(this).attr('name', this.name + '_' + new_id);
$(this).attr('value', 'test');
});
};
$(document).ready(function() {
$('#field_id').test()
});
<body>
<div id="container">
<input type="text" name="field_name" id="field_id" value="meh" />
</div>
</body>
所以我只能假设代码中还有其他内容。你能提供更多细节吗?
So I can only presume something else is going on in your code. Can you provide some more details?
这篇关于用jQuery设置新的id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!