![](/img/trans.png)
[英]How to change the “selected” text to “bold / unbold” which is present in input tag “using html and JavaScript” only
[英]How to change just the text after the bold tag?
我很难将“跑步者”的两个实例都更改为“队长”
<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/
使用全局开关( replace(/ a Runner/g," a Team Captain")
)来进行替换:
document.getElementById("thisForm").innerHTML=document.getElementById("thisForm").innerHTML.replace(/ a Runner/g," a Team Captain");
您的代码仅替换第一次出现的代码。 您可以将其转换为正则表达式并使用global match g
参数:
document.getElementById("thisForm").innerHTML = document.getElementById("thisForm").innerHTML.replace(/a Runner/g, " a Team Captain");
如果您希望使用jQuery实现,则可以通过直接更改textNode来避免浪费整个表的HTML。 尝试这个:
$('#thisForm td').each(function() {
var contents = $(this).contents().filter(function() {
return this.nodeType == 3;
});
contents[contents.length -1].nodeValue = " a Team Captain";
});
只需将搜索模式更改为带有全局(/ 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");
});
虽然j08691的答案是更好的选择,但这是替代方法。 下面的代码将使用jQuery遍历“跑步者”文本并将其更改为Team Captain。 通过使用类,我们可以遍历具有名称标题的元素的所有实例。
<b>Become</b> a <div class="title">Runner</div>
$(".title").each(function () {
$(this).html("Team Captain");
});
<p id="demo"><input type="radio" value="none" onclick="myFunction()" name="teamAct"><b>Become</b> a Runner</p>
函数myFunction(){var str = document.getElementById(“ demo”)。innerHTML; var res = str.replace(“亚军”,“队长”); document.getElementById(“ demo”)。innerHTML = res; }
试试这个
function myFunction() {
var str = document.getElementById("demo").innerHTML;
var res = str.replace("a Runner", "a Team Captain");
document.getElementById("demo").innerHTML = res;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.