替换innerHTML中的字符串 [英] Replacing string in innerHTML
问题描述
所以,这是我要完成的一件相当简单的事情(javascript),但是这花了我很长时间,但仍然无法正常工作.我正在尝试替换某些单词(位于pre标记内).例如,单词"static"
应该替换为
"<span class="keyword">static</span>"
.我使用严格的XHTML.
So, this is a fairly simple thing I'm trying to accomplish (javascript), but it's taking me ages and it still does not work. I'm trying to replace certain words (that are within a pre tag). For example, the word "static"
should be replaced by
"<span class="keyword">static</span>"
. I'm using XHTML strict.
我的方法是这样的:
for (var j = 0; j < keywords.length; j++)
{
codeBlock.innerHTML = codeBlock.innerHTML.replace(new RegExp(keywords[j], "g"), "<span class=\"keyword\">" + keywords[j] + "</span>");
}
codeBlock是前置元素,关键字是一个数组,其中包含我要替换的所有单词.
codeBlock is the pre element, keywords is an array that contains all the words I would like to replace.
我已经尝试了很多方法,但是我仍然遇到类似这样的错误消息.
I've tried so many ways, but I'm stuck with error messages like these.
Firefox:
[异常...指定了无效或非法字符串"代码:"12" nsresult:"0x8053000c(NS_ERROR_DOM_SYNTAX_ERR)"位置:"file:///C:/.../scripts.js行: 33]
[Exception... "An invalid or illegal string was specified" code: "12" nsresult: "0x8053000c (NS_ERROR_DOM_SYNTAX_ERR)" location: "file:///C:/.../scripts.js Line: 33"]
Chrome浏览器:
Chrome:
错误:INVALID_STATE_ERR:DOM异常11
Error: INVALID_STATE_ERR: DOM Exception 11
我猜想它与html标签有关(我尝试使用%lt;和%gt;代替),因为我知道这确实有效:
I'm guessing it has something to do with the html tags (I've tried using %lt; and %gt; instead), because I know that this does work:
codeBlock.innerHTML = codeBlock.innerHTML.replace(新 RegExp(keywords [j],"g"),"test");
codeBlock.innerHTML = codeBlock.innerHTML.replace(new RegExp(keywords[j], "g"), "test");
感谢您的宝贵时间, 雅科
Thanks you for your time, Jacco
推荐答案
您需要将代码包装在CDATA中
You will need to wrap your code in CDATA
<script type="text/javascript">
//<![CDATA[
for (var j = 0; j < keywords.length; j++)
{
codeBlock.innerHTML = codeBlock.innerHTML.replace(new RegExp(keywords[j], "g"), "<span class=\"keyword\">" + keywords[j] + "</span>");
}
//]]>
</script>
这样,您的代码将不会被解析为XHTML有效性.
This way your code will not be parsed for XHTML validity.
您当前的代码对我来说效果很好,网址为 http://jsfiddle.net/gaby/Y92AE/
Your current code works fine for me at http://jsfiddle.net/gaby/Y92AE/
这篇关于替换innerHTML中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!