我是JavaScript新手。我的代码This is a fiddle。
如果我删除CDATA
,那么它在小提琴上工作正常,但在像eclipse这样的XHTML编辑器上创建问题:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
这是我的JavaScript:
<![CDATA[
function test() {
alert(document.getElementById("divId"));
var regex = new RegExp('this',"gi");
document.getElementById("divId").innerHTML
= document.getElementById("divId").innerHTML.replace(regex,
function(matched)
{
return '<span class=\'highlight\'>' + matched + '</span>';
});
}
]]>
这是问题中的<div>
:
<div id="divId">
This is the text This is the text This is the text This is the text
This is the text This is the text This is the the text
</div>
我无法调用test()
功能。有什么建议吗?
答案 0 :(得分:5)
只需评论CDATA行:
...
// <![CDATA[
...
// ]]>
答案 1 :(得分:3)
包含在/ * * /之间
/*<![CDATA[*/
function test(){
alert(document.getElementById("divId"));
var regex = new RegExp('this',"gi");
document.getElementById("divId").innerHTML
=document.getElementById("divId").innerHTML.replace(regex, function(matched)
{
return '<span class=\'highlight\'>' + matched + '</span>';
});
}
/*]]>*/