0

この関数を呼び出して、エラーの種類を引数として渡し、メッセージを表示したい。

function msgDialog(msg) {
    // Define messages
    var errorMsg = "There has been an error.  We are sorry about that.";
    var loginMsg = "Something went awry with the login.  Please try again.";
    var uploadMsg = "Your upload failed.  Please try again.";
    var networkMsg = "You currently are not connected to the internet.  Please connect and try again.";
     alert(msg);
}

その関数 msgDialog(loginMsg) を呼び出して、正しいメッセージに割り当てることができる変数を取得し、それで何かを行うにはどうすればよいですか? ここでは警告していますが、実際には別の方法で表示します。arg 値の値を使用して新しい var を作成する必要があることはわかっていますが、その方法はわかりません。ありがとうございました。

4

1 に答える 1

4

これは純粋な JavaScript であり、jQuery ではありません。これを試して:

var msgDialog = (function() {
    var errors = {
        errorMsg : "There has been an error.  We are sorry about that.",
        loginMsg : "Something went awry with the login.  Please try again.",
        uploadMsg : "Your upload failed.  Please try again.",
        networkMsg : "You currently are not connected to the internet.  Please connect and try again."
    }

    return function(msg){
        alert(errors[msg]);
    }
})();

msgDialog('uploadMsg'); //  alerts "Your upload failed.  Please try again."

JavaScript のクロージャーを見たことがない場合は、ここで何が起こっているかを理解できます。

于 2013-04-09T02:14:28.463 に答える