我想调用这个函数,将错误类型作为参数传递,然后显示消息。
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/