1

编辑:至少部分问题是因为history已经存在(我不知道)。谢谢大家。

原来的:

我有一个函数将 an 的值推送到一个名为然后清除输入<input>的初始空全局数组中。history

推送值的代码在 Chrome 21 和 Opera 12 中运行良好,但在 IE9 和 Firefox 15 中却不行。

我一直在研究这个,发现如果数组是本地的(在 pr() 而不是 $(document).ready as 中创建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
}

先感谢您。

4

1 回答 1

2

您必须在 $(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
}
于 2012-09-18T05:03:45.643 回答