1

編集:少なくとも問題の一部は、historyすでに存在していたためです(そして、私はそれを知りませんでした)。みんな、ありがとう。

オリジナル:

<input>の値を名前付きの最初は空のグローバル配列にプッシュしhistory、入力をクリアする関数があります。

値をプッシュするコードは、Chrome 21 と Opera 12 では正常に機能しますが、IE9 と Firefox 15 では機能しません。

これについて少し調べてみたところ、配列がローカル ($(document).ready as ではなく pr() で作成) の場合、正常に機能することがわかりましたvar history = []。また、ファイルの先頭にあるすべてのものの外で宣言しようとしました。


エラー: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 に答える