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

标签 javascript jquery

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

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

最佳答案

这是纯 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."

您可以了解发生了什么 here如果您之前没有见过 JavaScript 闭包。

关于javascript - 使用 jQuery,如何将 arg 传递给函数,然后显示来自预定义变量的消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15892119/

相关文章:

php - 在 PHP5.1.6 上运行时获取 json 为 null 输出

javascript - 获取未捕获的类型错误 : RulesModule. ruleModals 不是函数

javascript - 空值会导致 NaN 结果

javascript - 在 d3 中添加刻度线

javascript - 当你点击每个单词/名字时,你是如何得到某些div显示的?

javascript - 如何在SoundManager2中添加歌曲进度条?

javascript - 代码返回未定义而不是返回值

javascript - RXJS5 像 Promise 一样链接

javascript - 如何使用 jQuery 将 div 的滚动条保留在 div 的底部?

javascript - javascript 的窗口宽度条件