2012-09-18 27 views
1

編輯:至少部分問題是因爲history已經存在(我不知道)。感謝大家。jQuery - 如何將值推入IE和Firefox中的全局數組?

原文:

我有一個推動的<input>值到一個名爲history初始爲空的全局數組然後清除輸入的功能。

推值的代碼工作正常,在Chrome 21和Opera 12,但不是在IE9和Firefox 15

我一直在研究這個了一下,發現如果陣列的本地(創建在pr()而不是$(文檔).ready爲var history = []),它工作正常。我也試着在文件頂部的所有內容之外聲明它。


IE錯誤:SCRIPT438: Object doesn't support property or method 'push'

FF錯誤:TypeError: history.push is not a function


如何推動一個值,在IE和Firefox空全局數組?

這裏是我的代碼:

<input type="text" id="command" /> 

然後在我的JS文件:

$(document).ready(function() { 
    history = []; // no var because that makes it global, right? 
)}; 

$(document).keypress(function(e) { 
    if(e.which == 13) { // if enter  
     e.preventDefault(); 

     if($("#command").val() !== "") { 
      pr(); 
     } 
    } 
}); 

function pr() { 
    var text = $("#command").val(); 

    text = text.replace(/<(?:.|\n)*?>/gm, ""); // these two are supposed to 
    text = text.replace(/[<>]/gi, "");   // sanitize the input 

    history.push(text); // this where it gets hairy 
    alert(history); // doesn't display anything in IE/FF because .push failed 

    // do a bunch of other stuff that isn't relevant 
} 

預先感謝您。

+3

稱之爲「歷史」以外的東西。 – ahren

+0

不確定是否有打字錯誤,但是$(document).ready(function(){)沒有正確關閉,並且您可以通過去窗口輕鬆地從任何地方聲明全局變量<變量名> = ... –

+0

也是歷史記錄非常糟糕的名字,因爲歷史已經是一個對象,很可能是問題,將它重命名爲scriptHistory –

回答

1

您必須在$(document).ready()之外聲明var,同時請注意歷史記錄在瀏覽器中已經是一個全局變量。

// I changed the variable name. from history to historyVar 
var historyVar = []; // this makes it global 


$(document).ready(function() { 
    // FIX: declaring it here will not make it global to your js. 
    // history = []; // no var because that makes it global, right? 
}); // **NOTE: was not properly closed, I added some); to do the fix** 

$(document).keypress(function(e) { 
    if(e.which == 13) { // if enter  
     e.preventDefault(); 

     if($("#command").val() !== "") { 
      pr(); 
     } 
    } 
}); 

function pr() { 
    var text = $("#command").val(); 

    text = text.replace(/<(?:.|\n)*?>/gm, ""); // these two are supposed to 
    text = text.replace(/[<>]/gi, "");   // sanitize the input 

    historyVar.push(text); 

    // do a bunch of other stuff that isn't relevant 
} 
+1

感謝您的回答。問題的一部分是「歷史」已經作爲一個內置對象存在。 – Abluescarab

+1

除了不叫它歷史,它是瀏覽器歷史的對象,你也可以使用window.variableName強制它進入全局範圍 –

+0

D'OH!我完全忘了那個,在大多數瀏覽器中,Yep歷史是一個對象,我會修改我的ans WER。 – nmenego