0

我想调用这个函数,将它作为 arg 的错误类型传递,然后显示消息。

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) 并拥有一个可以分配给正确消息的 var,然后用它做些什么?我在这里提醒它,但我真的会以不同的方式显示它。我知道我需要使用 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 回答