使用text()显示javascript代码

Display javascript code with text()

本文关键字:javascript 代码 显示 text 使用      更新时间:2023-09-26

我试图使用jQuery text()方法在预/代码标签中显示一些javascript。这样的:

 jQuery(".output").wrapInner( "<pre><code></code></pre>" );
 jQuery(".output code").text("<script type='text/javascript' src='http://somedomain/?" + apiKeyValue.val() + "></script>");

但是脚本标签产生一个

Uncaught SyntaxError: Unexpected token ILLEGAL

控制台出现

错误。如何显示脚本标签?

Replace

jQuery(".output code").text("<script type='text/javascript' src='http://somedomain/?" + apiKeyValue.val() + "></script>");

:

jQuery(".output code").text("<script type='text/javascript' src='http://somedomain/?" + apiKeyValue.val() + "></"+"script>");

或:

jQuery(".output code").text("<script type='text/javascript' src='http://somedomain/?" + apiKeyValue.val() + "><'/script>");

您需要打破</script>标签("</"+"script>")或转义/ ("<'/script>")

正如TreeTree在评论中指出的那样,要了解详细的解释,请阅读为什么拆分脚本<标记时写它与document.write()?>