如何在javascript中用字符串变量替换一段文本

How do I replace a bit of text with string variable in javascript?

本文关键字:文本 一段 替换 变量 javascript 字符串      更新时间:2023-11-17

我知道这是一个非常简单的问题,但每次偶数触发时,我都需要用变量替换段落中的这段文本。

标记看起来像这个

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
#container {width:100%; text-align:center; }
#heading {width:100%; text-align:center; }
</style>
</head>
<div id="heading">
<h1>hello</h1> 
</div> 
<body>
<div id="container">
<textarea name="mytextarea" cols="60" rows="40"></textarea>
</div>
</body>
</html>

我需要的是它在标签中说"你好"的地方,让它成为一个变量,用我将生成的字符串替换它。

您可以创建一个类似这样的函数。

function replaceTitle (replaceText) {
    document.getElementById("heading").getElementsByTagName("h1")[0].innerHTML = replaceText;
}

如果您使用的是jQuery,它可能更像这样。

function replaceTitle (replaceText) {
    $("#heading h1").html(replaceText);
}

然后你调用类似的函数

replaceText(yourVariable);

最好给<h1>标签一个id或类,这样你就可以直接引用它,但我认为你有充分的理由不这样做。

关于如何将简单的事情变得复杂的一个例子:)

javascript:

// simple way:
function replace_text(text) {
    var heading = document.getElementById('heading');
    heading.innerHTML = '<h1>' + text + '</h1>';
}
// complicated way:
function replace_text2(text) {
    var heading = document.getElementById('heading');
    var node = heading.childNodes[0];
    while ( node && node.nodeType!=1 && node.tagName!='H1' ){
        //console.log(node.nodeType,node);
        node = node.nextSibling;
    }
    if (node) {
        node.replaceChild(document.createTextNode(text),node.childNodes[0]);
    }
}

html:

<input type="button" onclick="replace_text('HELLO 1!');" value="Replace 1st text" />
<input type="button" onclick="replace_text2('HELLO 2!');" value="Replace 2nd text" />

剧本在这儿。