2012-09-18 23 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