saber 酱的抱枕

Fly me to the moon

06/14
2017
学习

在script标签中输出script标签出错的解决办法

如果我们在JavaScript里想输出一个script标签,可以这样写:

document.writeln("<script>alert('xx');</script>");

但如果是在html文件里的script标签里这样写,就会出现语法错误:

<script>
document.writeln("<script>alert('xx');</script>");
</script>

javascript js script标签 语法错误

在编辑器里面也能看出来异常,本来红框内是字符串,应该都是黄色的,但是显示的不对,原因就是在html里会把结束标记的字符串
“</script>”解析成标签,导致了错误。

解决办法是把导致错误的这个结束标记拆开再拼接起来:

<script>
document.writeln("<script>alert('xx');</scr"+"ipt>");
</script>

在script标签中输出script标签出错的解决办法

  1. Google Chrome 45Google Chrome 45WindowsWindows

    我记得有更原生的做法:
    ```js
    function addScriptTag(url) {
    var ds = document.createElement('script');
    ds.type = 'text/javascript';ds.async = true;
    ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + url;
    ds.charset = 'UTF-8';
    (document.getElementsByTagName('head')[0]
    || document.getElementsByTagName('body')[0]).appendChild(ds);
    };
    ```

    回复

评论 zthxxx 撤销评论