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

时间:2012-07-19 10:56:29

标签: javascript dom

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

标记看起来像这样

"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>

我需要的是标签中的“hello”,它是一个变量,可以被我将生成的字符串替换。

2 个答案:

答案 0 :(得分:1)

你可以创建一个看起来像这样的函数。

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

如果您使用 jQuery ,它可能看起来更像这样。

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

然后你调用这个函数

replaceText(yourVariable);

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

答案 1 :(得分:0)

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

的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" />

The script is here