Javascript Replace() 和 innerHTML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3578450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript Replace() and innerHTML
提问by James
I have this code: [it is a rough example with poor coding, but it illustrates what I want to do.]
我有这个代码:[这是一个粗略的例子,编码很差,但它说明了我想要做什么。]
<html>
<body>
<script type="text/javascript">
function fun()
{
var divs = document.getElementById('hi');
divs.innerHTML = divs.innerHTML.replace("cake","jump");
alert(divs.innerHTML);
}
</script>
<div id="hi">
<span onclick="fun('cake');">Mer<span onclick="fun('cake');">Mer</span></span>
</div>
<a onclick='fun()';)>Click</a>
</body>
</html>
When I click on the <a>i want to change the onclick parameter within fun() from 'cake' to 'jump'. I do not want to use the setAttribute() method as my real example has several nested tags and I want to replace 'cake' in several different places.
当我单击时,<a>我想将 fun() 中的 onclick 参数从“cake”更改为“jump”。我不想使用 setAttribute() 方法,因为我的真实示例有几个嵌套标签,我想在几个不同的地方替换“蛋糕”。
I want the innerHTML.replace() function to work to do this but, alas it doesn't function as I want it to. How do I replace text within innerHTML?
我希望 innerHTML.replace() 函数可以执行此操作,但是,可惜它没有按我希望的那样运行。如何替换innerHTML 中的文本?
回答by bobince
Forget it. Never hack around with the innerHTML, there's no guarantee it will be in any particular format, you're very likely to mess up the markup by replacing the wrong thing, and even if it works, you're serialising the document content into a string, hacking it and then recreating the entire content from the string again, instead of just replacing a particular thing you're interested in. This is slow and loses all non-serialisable data (like form field values, JS references and assigned event handlers).
忘了它。永远不要innerHTML乱用,不能保证它会采用任何特定格式,您很可能通过替换错误的内容来弄乱标记,即使它有效,您也将文档内容序列化为字符串,破解它,然后再次从字符串中重新创建整个内容,而不是仅仅替换您感兴趣的特定内容。这很慢并且会丢失所有不可序列化的数据(如表单字段值、JS 引用和分配的事件处理程序)。
In general DOM methods are much more reliable for altering page content. It's what they were designed for. Use them, and use the DOM Level 1 HTML properties in preference to setAttributewhich is badly broken in IE. This goes double for event handler attributes. Trying to hack at JavaScript code insidean attribute value insidean HTML string is insanity, even if it worked.
一般来说,DOM 方法对于更改页面内容要可靠得多。这就是它们的设计目的。使用它们,并优先使用 DOM Level 1 HTML 属性,setAttribute而不是在 IE 中被严重破坏。这对于事件处理程序属性来说是双倍的。试图在JavaScript代码破解里面的属性值内的HTML字符串是精神错乱,即使它的工作。
There is no need whatsoever to replace any page content. You could implement your example much more easily with a simple variable:
无需替换任何页面内容。您可以使用一个简单的变量更轻松地实现您的示例:
<div id="hi">
<span>Mer<span>Mer</span></span>
</div>
<a id="foo">Click</a>
<script type="text/javascript">
var potato= 'cake';
document.getElementById('foo').onclick= function() {
potato= 'jump';
return false;
};
var spans= document.getElementById('hi').getElementsByTagName('span');
for (var i= spans.length; i-->0;) {
spans[i].onclick= function() {
alert(potato); // do whatever with the variable
};
}
</script>
回答by Richard JP Le Guen
First, you have an error in your HTML:
首先,您的 HTML 中有错误:
<a onclick='fun()';)>Click</a>
What's with the ;)outside the attribute value?
;)属性值的外面是什么?
Next...
下一个...
[...] method as my real example has several nested tags and I want to replace 'cake' in several different places.
[...] 方法作为我的真实例子有几个嵌套标签,我想在几个不同的地方替换“蛋糕”。
This means you really, reallydon't want to use innerHTMLand replace(). It willscrew up. Use an HTML parser of sorts; walk the DOM recursively... anything other than replace.
这意味着你真的,真的不想使用innerHTMLand replace()。它会搞砸。使用各种 HTML 解析器;递归地遍历 DOM ......除了replace.
Within the scope of your specific example, I suggest using a variable to hold the value of cakeand jumpinstead.
在您的具体示例的范围内,我建议使用一个变量来保存cakeand的值jump。
回答by palswim
Change your replacecall to use the RegEx "global"flag:
更改您的replace调用以使用RegEx“全局”标志:
divs.innerHTML = divs.innerHTML.replace(/cake/g,"jump");
That said, if you're using this for more than a quick test, you should use DOM objects to accomplish what you would like to do. Otherwise, this will get ugly really fast.
也就是说,如果您将它用于快速测试,那么您应该使用 DOM 对象来完成您想做的事情。否则,这会很快变得丑陋。
Also, it wouldn't hurt to change your <a>tag code:
此外,更改<a>标签代码也无妨:
<a onclick='fun(); return false;')>Click</a>
(The return false;is optional, but good practice.)
(这return false;是可选的,但很好的做法。)
回答by Douglas
The easiest way to change the onclick parameter is to make it a variable instead of a string literal. Here I'm using a variable called food:
更改 onclick 参数的最简单方法是将其设为变量而不是字符串文字。在这里,我使用了一个名为 的变量food:
<script type="text/javascript">
var food = "cake";
function change()
{
food = "jump";
}
</script>
<div id="hi">
<span onclick="alert(food);">Mer<span onclick="alert(food);">Mer</span></span>
</div>
<a onclick='change()'>Click</a>

