用jQuery设置新的id

sch*_*eck 27 javascript jquery

"this"是文本字段,"new_id"是整数.

当我应用以下代码段时:

$(this).attr('id',   this.id + '_' + new_id);
$(this).attr('name', this.name + '_' + new_id);
$(this).attr('value', 'test');
Run Code Online (Sandbox Code Playgroud)

id更改,名称也会更改,但不会更改.如果我将最后一行更改为此(因此使用字符串文字)

$('#mytextfield_3').attr('value', 'test');
Run Code Online (Sandbox Code Playgroud)

有用.

有任何想法吗?

- 编辑 - 感谢Steerpike的快速插件测试 - 我相信它应该可行,但我找不到错误.

这是一些更多的代码:

我使用创建克隆

clone = $(this).find('.clone_fields_container:first').clone();
Run Code Online (Sandbox Code Playgroud)

"clone"现在包含一个嵌入了输入字段的div.

生成新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);
  });
Run Code Online (Sandbox Code Playgroud)

文本字段没有任何值.

Ste*_*ike 29

我刚刚编写了一个快速插件来使用相同的代码片段运行测试,它运行正常

$.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>
Run Code Online (Sandbox Code Playgroud)

所以我只能假设你的代码中正在发生其他事情.你能提供更多细节吗?

  • 你是对的,经过半夜的调试,我发现将 .html() 编辑与直接节点操作混合在一起并不好......无论如何,你的代码让我找到了解决方案,非常感谢。 (2认同)