2012-03-20 121 views
1

的一部分,我有以下代码:的jQuery替换字符串

​<div id="container"> 
<input type="text" name="a1" id="a1"> 
<input type="text" name="a2" id="a2"> 
​</div>​​​​​​​​​​​​​​​​ 

我要替换文本的所有实例“一”到“B”的标识和名称属性里面的所有元素DIV ID =“容器”

所以新的代码应该是这样的:

​<div id="container"> 
<input type="text" name="b1" id="b1"> 
<input type="text" name="b2" id="b2"> 
​</div>​​​​​​​​​​​​​​​​ 

我似乎没有能够使它工作使用JavaScript替换()。

+4

让我们看看你已经尝试过的代码。另外,你显然不想用'b'替换_all_'a',因为你最终会得到类似'''的标记。那么你究竟想要做什么? – 2012-03-20 13:42:04

回答

6
$('#container input').each(function(){ // Loop through all inputs 
    this.name = this.name.replace('a', 'b'); // Replace name 
    this.id = this.id.replace('a', 'b'); // Replace ID 
}); 

DEMO:http://jsfiddle.net/G3vCf/

1
$('#a1').attr('name', 'b1').attr('id', 'b1'); 
$('#a2').attr('name', 'b2').attr('id', 'b2'); 
0
$("#container").children("input").each(function() { 
    var name = $(this).attr("name"); 
    var id = $(this).attr("id"); 

    name = name.replace(/a/g, "b"); 
    id = id.replace(/a/g, "b"); 

    $(this).attr("name", name); 
    $(this).attr("id", id); 
}); 
0

这里

$(function(){ 
    var html =$('#container').html().replace(/a/g,'b'); 
    $('#container').html(html);​ 
}); 

Example