2013-04-24 60 views
2

我在頁面上使用Google code prettify(正常工作),並且我想添加一個函數,一旦此過程完成,就會調用該函數。在谷歌代碼中使用回調美化代碼

在文檔,它們描述了以下參數:

callback=js_ident window.exports["js_ident"] will be called when prettyprinting finishes. If specified multiple times, all are called. 

但是,我一直沒能得到這個工作對我來說。我明顯錯過了應該如何定義/導出回調函數。

我的頭看起來像這樣(在頁面加載時的代碼是正確的美化,但警告不顯示):

<script type='text/javascript'>function testing(){alert('hello')}}</script> 
<script type='text/javascript' src='https://google-code-prettify.googlecode.com/svn/loader/prettify.js?callback=testing'></script> 

此外,以下this example,我曾嘗試在幾個不同的修改第一塊方法()如下圖所示一對夫婦),但沒有改變:

<script type='text/javascript'>window['exports'] = {testing: function(){alert('123')}}</script> 
<script type='text/javascript'>window.exports = {testing: {apply: function(){alert('123')}}}</script> 

我怎麼來定義我的testing功能,因此它可以被稱爲正確?

回答

4

看起來callback參數只適用於run_prettify.js腳本,而不是您目前使用的prettify.js腳本。

此外,per the docs,他們希望你在callback參數指定的函數在window.exports對象指定。

E.g http://jsbin.com/atukuq/1/

<script type='text/javascript'> 
    window.exports = { 
    testing: function() { 
     alert('hello'); 
    } 
    } 
</script> 
<script src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js?callback=testing"></script> 
+0

我完全錯過了我使用'prettify.js'而不是'run_prettify.js'!這正是我需要的,非常感謝。 – Ben 2013-04-24 13:34:16

+0

@Ben:沒問題,有時你需要一雙不同的眼睛;) – Matt 2013-04-24 13:38:50

+0

順便說一句,'window.exports'是一個標準的還是內置的對象?在我研究這個問題時,我沒有找到關於它的很多信息。他們在文檔中描述它的方式使得這樣做似乎是一種標準做法,是這樣嗎? – Ben 2013-04-24 13:40:10

2
<script type='text/javascript'> 
    window.exports = []; 
    window.exports["testing"] = function() { 
     alert("hello"); 
    } 
</script> 
<script type='text/javascript' src='https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js?callback=testing'></script> 

的變化:run_prettify.js代替prettify.js並且根據文檔定義的函數。