2013-07-03 106 views
2

我是JavaScript新手。 This is a fiddle与我的代码。无法呼叫测试()

如果我删除CDATA那么它适用于小提琴正常,但在XHTML编辑器创建问题,如Eclipse:

<!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

什么是 “无法” 是什么意思?你有错误吗?你是怎么称呼它的? – Zim84

+5

我的建议?停止使用xHTML(特别是Transitional)并切换到HTML5。对于初学者,您不需要丑陋的CDATA评论符号。 ;) –

+0

由无法我的意思functio不是calls.i没有发现任何错误 – viki

回答

5

只是评论CDATA线:

... 
// <![CDATA[ 
... 
// ]]> 
+0

我不能评论,因为我在我的问题中提到..看到这个http://stackoverflow.com/questions/17443461/javascript-code-not-working-in-jsf-xhtml-page/17443517?noredirect=1#comment25340917_17443517 – viki

+0

@viki你可以。这些注释仅适用于JavaScript,XML解析器仍可识别CDATA部分。 – Uooo

+0

@viki出于好奇,你甚至读过[关于CDATA的维基百科文章](http://en.wikipedia.org/wiki/CDATA)我链接了我的[最后回答](http://stackoverflow.com/ a/17443517/1328300)你以前的问题?它明确地[在XHTML中显示它的用法](http://en.wikipedia.org/wiki/CDATA#Use_of_CDATA_in_program_output)。请确保你了解**为什么它以这种方式工作。 – Uooo

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>'; 
     }); 


    } 

/*]]>*/