如何更改粗体标记后的文本?

时间:2014-08-13 13:36:09

标签: javascript jquery

我很难将“跑步者”的两个实例改为“队长”

<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">
                &nbsp;<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">
                &nbsp;<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/

6 个答案:

答案 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");

Updated fiddle

如果您想要一个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";
});

Example fiddle

答案 2 :(得分:0)

只需将搜索模式更改为带有全局(/ g)标志的正则表达式对象:

$('#thisForm').html(function(i, html) {
    return html.replace(/a Runner/g," a Team Captain");
});

Demo

这也可以轻松扩展到每行操作,允许首先应用过滤器:

$('#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的元素的所有实例。

&nbsp;<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; 
}