使用jQuery,如何将参数传递给函数,然后显示来自预定义变量的消息

Using jQuery, how do I pass arg to function and then display a message from predefined variable

本文关键字:预定义 显示 变量 消息 然后 函数 jQuery 参数传递 使用      更新时间:2023-09-26

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

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,但不确定如何创建。谢谢你。

这是纯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闭包,你可以了解这里发生了什么。