2009-04-22 66 views
18

“this”是一个文本字段,“new_id”是一个整数。使用jQuery设置新ID

当我申请了下面的代码片段:

$(this).attr('id', this.id + '_' + new_id); 
$(this).attr('name', this.name + '_' + new_id); 
$(this).attr('value', 'test'); 

的ID改变,名称也发生了变化,而不是价值。如果我改变最后一行此设置(使用字符串字面)

$('#mytextfield_3').attr('value', 'test'); 

它的工作原理。

任何想法?

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

这里的一些代码:

我创建使用

clone = $(this).find('.clone_fields_container:first').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); 
    }); 

的文本字段不具有任何价值。

+0

是您在更改文档后对于该文档仍然是唯一的ID吗? – fredrik 2009-04-22 21:38:10

+0

是的,我改变它后,它是独一无二的 – schneck 2009-04-22 21:48:12

回答

22

我只是写了一个快速的插件使用相同的代码段运行测试,它工作正常

$.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> 

会发生什么所以我只能假设其他代码正在执行。你能提供更多的细节吗?

0

编辑:根据您的评论,并假设this是克隆的元素。

$(this).clone() 
     .attr('id', this.id + '_' + new_id) 
     .attr('name', this.name + '_' + new_id) 
     .val('test') 
     .appendTo('#someElement'); 

完整的例子

<script type="text/javascript"> 
    var new_id = 0; 
    $(document).ready(function() { 
     $('#container > input[type=button]').click(function() { 
      var oldinp = $('input#inp')[0]; 
      var newinp = $(oldinp).clone() 
            .attr('id',oldinp.id + new_id) 
            .attr('name',oldinp.name + new_id) 
            .val('test') 
            .appendTo($('#container')); 
      $('#container').append('<br>'); 
      new_id++; 
     }); 
    }); 
</script> 


<div id="container"> 
<input type="button" value="Clone" /><br/> 
<input id="inp" name="inp" type="text" value="hmmm" /><br/> 
</div> 
+0

不幸的是,这并不是很好。 – schneck 2009-04-22 21:28:56

1

你尝试

$(this).val('test'); 

,而不是

$(this).attr('value', 'test'); 

val()一般是比较容易的,因为您需要更改的属性在不同的DOM元素上可能会有所不同。

0

当你设置的所有属性的一个attr() command像这样

$(this).attr({ 
       id : this.id + '_' + new_id, 
       name: this.name + '_' + new_id, 
       value: 'test' 
      }); 
0

使用.val()不是attr('value')