2

我是 JavaScript 新手。这是我的代码的一个小提琴

如果我删除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()函数。有什么建议么?

4

2 回答 2

5

只需评论 CDATA 行:

...
// <![CDATA[
...
// ]]>
于 2013-07-03T10:27:53.027 回答
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>';
        });


    }

/*]]>*/
于 2013-07-03T10:27:29.440 回答