如何在javascript中用字符串变量替换一段文本
How do I replace a bit of text with string variable in javascript?
我知道这是一个非常简单的问题,但每次偶数触发时,我都需要用变量替换段落中的这段文本。
标记看起来像这个
"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" />
剧本在这儿。
相关文章:
- 在一段时间内切换文本
- 如何停止字幕文本一段时间,然后继续
- 如何使用jquery/js/css逐步突出显示一段文本
- 如何成功显示和隐藏一段文本
- 如何在javascript中用字符串变量替换一段文本
- 如何在一段时间后更改文本的颜色
- 仅显示变量内的一段文本
- 如何从HTML页面的源代码中获取一段文本
- Jquery 在文本中淡出一段时间
- Javascript获取HTML块中的最后一段文本
- 如何用JavaScript/jQuery替换和缩短一段文本中的超链接
- 如何在网站上制作动画,每秒钟就会有一段文本发生变化
- Javascript:如何找到在长段落中选择了特定文本的哪个实例(例如,一个单词在一段中出现多次)
- 如何使用JavaScript中的正则表达式删除一段跨越多行的文本
- 将一段内容从.txt文件粘贴到文本区域
- 给定一段文本,如何获取从开头到最后一个空格的所有内容
- 从一段文本中找出javascript中的关键字
- 如何切换页面的一个部分,使其从一段文本转到另一段文本
- 如何在jquery中更改标题中的文本一段时间
- 显示文本一段时间