我很难将“跑步者”的两个实例改为“队长”
<form id="thisForm">
<table>
<tr bgcolor="#eeeeee">
<td valign="top" colspan="4" style="vertical-align: top;">
<input type="radio" onclick="javascript:teamAction('form')" value="none" name="teamAct">
<b>Become</b> a Runner
</td>
</tr>
<tr bgcolor="#eeeeee">
<td valign="top" colspan="4" style="vertical-align: top;">
<input type="radio" onclick="javascript:teamAction('form')" value="none" name="teamAct">
<b>Support</b> a Runner
</td>
</tr>
</table>
</form>
我能够使用:
更改第一个实例document.getElementById("thisForm").innerHTML = document.getElementById("thisForm").innerHTML.replace(" a Runner", " a Team Captain");
请参阅jsfiddle:http://jsfiddle.net/jelane20/voxnmwpn/
答案 0 :(得分:2)
将全局开关(replace(/ a Runner/g," a Team Captain")
)与您的替换:
document.getElementById("thisForm").innerHTML=document.getElementById("thisForm").innerHTML.replace(/ a Runner/g," a Team Captain");
<强> jsFiddle example 强>
答案 1 :(得分:0)
您的代码仅替换第一次出现。您可以将其转换为正则表达式并使用全局匹配g
参数:
document.getElementById("thisForm").innerHTML = document.getElementById("thisForm").innerHTML.replace(/a Runner/g, " a Team Captain");
如果您想要一个jQuery实现,您可以通过直接更改textNodes来避免重置整个表的HTML。试试这个:
$('#thisForm td').each(function() {
var contents = $(this).contents().filter(function() {
return this.nodeType == 3;
});
contents[contents.length -1].nodeValue = " a Team Captain";
});
答案 2 :(得分:0)
只需将搜索模式更改为带有全局(/ g)标志的正则表达式对象:
$('#thisForm').html(function(i, html) {
return html.replace(/a Runner/g," a Team Captain");
});
这也可以轻松扩展到每行操作,允许首先应用过滤器:
$('#thisForm tr').html(function(i, html) {
return html.replace(/a Runner/g," a Team Captain");
});
答案 3 :(得分:0)
虽然j08691的答案是更好的选择,但这是另一种选择。下面的代码将使用jQuery循环遍历你的&#34; Runner&#34;文本并将其更改为Team Captain。通过使用类,我们可以循环遍历名称为title的元素的所有实例。
<b>Become</b> a <div class="title">Runner</div>
$(".title").each(function () {
$(this).html("Team Captain");
});
答案 4 :(得分:0)
<p id="demo"><input type="radio" value="none" onclick="myFunction()" name="teamAct"><b>Become</b> a Runner</p>
function myFunction(){var str = document.getElementById(&#34; demo&#34;)。innerHTML; var res = str.replace(&#34;跑步者&#34;,&#34;队长&#34;); document.getElementById(&#34; demo&#34;)。innerHTML = res; }
答案 5 :(得分:-1)
试试这个
function myFunction() {
var str = document.getElementById("demo").innerHTML;
var res = str.replace("a Runner", "a Team Captain");
document.getElementById("demo").innerHTML = res;
}