2014-09-04 67 views
1

我正在編寫一個UserScript,一切正常,直到現在,當我點擊一個按鈕時,我應用了一個onClick屬性,控制檯一直告訴我Uncaught ReferenceError: SB_Change is not defined和功能SB_Change(what)將不會執行。Uncaught ReferenceError:<我的用戶腳本定義的函數>未定義

代碼:

window.addEventListener('load', function() { 
    var but1 = document.createElement("BUTTON"); 
    var t1=document.createTextNode(" + "); 
    but1.style.width = "16px"; 
    but1.style.height = "16px"; 
    but1.appendChild(t1); 
    but1.setAttribute('onclick','SB_Change("+")'); 
    // - 
    var but2 = document.createElement("BUTTON"); 
    var t2=document.createTextNode(" - "); 
    but2.appendChild(t2); 
    but2.style.width = "16px"; 
    but2.style.height = "16px"; 
    but2.setAttribute('onclick','SB_Change("-")'); 
    // - 
    var SB_text = document.getElementById("shoutbox").getElementsByTagName("h3")[0]; 
    SB_text.innerHTML = "Shoutbox "; 
    SB_text.appendChild(but1); 
    SB_text.appendChild(but2); 

    function SB_Change(type){ 
     var H = document.getElementById("sbPosts").maxHeight; 
     switch(type){ 
      case "+": 
       H = "800px"; 
       break; 
      case "-": 
       H = "400px"; 
       break; 
     } 
    } 
}, false); 

回答

1

兩個問題:

  1. 功能SB_Change被負載函數範圍內限定。當你點擊一個鏈接時,這個範圍不再存在。
    移動定義負載處理外,像這樣:

    window.addEventListener ('load', function() { 
        ... ... 
    }, false); 
    
    function SB_Change (type){ 
        ... ... 
    } 
    
  2. 否則,這個問題是Uncaught ReferenceError: function is not defined with onclick重複。
    除非(a)您故意注入代碼或(b)在支持它的引擎上使用@grant none模式,否則用戶腳本將被沙盒化。 (除非絕對必要,否則不推薦使用這兩種模式。)

    請勿使用onclick(以上!)。看到重複的問題。

+0

謝謝你,我喜歡你說的,但它不工作。也許是因爲我的功能有爭議?反正繼承我新的代碼:http://pastebin.com/LQmn1NEr它不告訴我「SB_Change沒有定義..:」當我點擊一個按鈕時,它什麼也不做,當我輸入SB_Change(「+ 「)進入控制檯,比它聲明SB_Change未定義 – PoTTii 2014-09-05 18:15:06

+0

新代碼不正確地使用'addEventListener'。另外,一般來說,您不能在控制檯中使用userscript函數。但是,在這種情況下,您可以通過將其定義爲:'window.SB_Change = function(type){'。無論如何,你需要爲這些新問題開一個新的問題。 – 2014-09-05 23:43:06

相關問題