如何在JavaScript中替换一些字符串变量的文本? [英] How do I replace a bit of text with string variable in javascript?
本文介绍了如何在JavaScript中替换一些字符串变量的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道这是一个非常简单的问题,但是我需要在每次平均触发时用一个变量替换一段段落中的文本。
I know this is a really simple question, but I need to replace this bit of text in a paragraph with a variable every time an even fires.
标记看起来像这样
"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的地方,就是将它变成一个变量那辆面包车将被我将生成的一个字符串所替代。
What I need is where it says "hello" in the tags, is for that to be a variable that van be replaced by a string that I will generate.
推荐答案
一个例子,简单的事情如何变得复杂:)
One example on how can be simple things made complicated :)
javascript:
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" />
这篇关于如何在JavaScript中替换一些字符串变量的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文