简体   繁体   English

美化prettyPrint()函数未加载到内部<script> tag

[英]Prettify prettyPrint() function not loading inside <script> tag

I'm using Googles prettify.js and prettify.css files hosting them myself. 我正在使用自己托管的Google的prettify.js和prettify.css文件。 This is a javascript and css script that highlights source code snippets inside <pre> or <code> tags. 这是一个JavaScript和CSS脚本,突出显示<pre><code>标记内的源代码片段。 Doc can be found here: https://github.com/google/code-prettify/blob/master/docs/getting_started.md 可以在以下位置找到文档: https//github.com/google/code-prettify/blob/master/docs/getting_started.md

To initialize the script, it can to be called like this: <body onload="prettyPrint();"> which works fine. 要初始化脚本,可以这样调用它: <body onload="prettyPrint();">可以正常工作。

I don't want to add this attribute to all the <body> tags of my pages, instead i want to call it from a <script> tag inside the <body> , (for reasons a bit long to explain). 我不想将此属性添加到页面的所有<body>标记中,相反,我想从<body>内的<body> <script>标记中调用它(出于较长时间的解释)。 But this doesn't work. 但这是行不通的。

Here is the code: 这是代码:

<body>
    <script type="text/javascript">
        prettyPrint();
        //document.write('doing something');//this line prints
    </script>
    ...

The code snippet is not getting highlighted as it did when i called the function through <body onload="prettyPrint();"> but there is no error on the JavaScript console, and the line 'doing something' is printing. 代码片段没有像我通过<body onload="prettyPrint();">调用该函数时那样突出显示,但是JavaScript控制台上没有错误,并且'doing something'行。

How can i call this function from the <script> tag? 如何从<script>标记调用此函数?

EDIT 编辑

Even this is printing but still the syntax is not getting highlighted: 即使正在打印,但语法仍未突出显示:

<body>
    <script type="text/javascript">
        if(window.prettyPrint){
            prettyPrint();
            document.write('doing something');//this line prints
        }
    </script>
    ...

So, it has to be called using object.onload i don't really know why i just tried a lot of things and this worked. 因此,必须使用object.onload来调用它,我真的不知道为什么我只是尝试了很多事情而这行得通。 Actually it makes a lot of sense anyways. 实际上,无论如何,这很有意义。

    <body>
        <script>
            window.onload=function(){prettyPrint();};
        </script>
        ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM