如何解决如何使用字典在 JavaScript 返回值中实现回调
我正在尝试实现一个具有键和值的 JS 字典,其中值调用回调函数进行验证。
例如,我尝试定义一个animalsDict 字典。 当我尝试调用“Dog”键来调用值 validateDogSound() 回调函数时,bootbox.alert 不显示。
我做错了什么?这就是我们在字典中执行回调函数的方式吗?任何提示或帮助?谢谢
var animalsDict = {
Dog: validateDogSound(),//Cat: validateCatSound(),//Bird: ... etc
}
function validateDogSound(){
bootbox.alert("dogs bark!");
return false;
}
console.log('testDog',animalsDict["Dog"]);
解决方法
您需要调用函数:
console.log('testDog',animalsDict["Dog"]());
// ^
同时将对象更改为
var animalsDict = {
Dog: validateDogSound,//Cat: validateCatSound,//Bird: ... etc
}
,
这边
// "functions" first !
var validateDogSound = function()
{
bootbox.alert("dogs bark!");
return false;
}
var animalsDict = {
Dog: validateDogSound,// no parenthesis
//Cat: validateCatSound,//Bird: ... etc
}
console.log('testDog',animalsDict["Dog"]() ); // with parenthesis
,
根据documentation,您需要按以下顺序加载javascript库。
由于 Bootbox 是 Bootstrap 模态功能的包装器,因此您需要按顺序包含这些库:
jQuery
Popper.js
Bootstrap
Bootbox
Bootbox Locales (optional - omit if you only need the default English locale)
尝试以相同的顺序添加这些标题或使用以下内容。我在标题中添加了以下内容,看起来它有效。你会知道的更好。 请注意,我没有验证这些网址,这只是为了演示。如果您的服务器上有这些网址的本地副本并且在头部适当引用,那就更好了。
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/5.5.2/bootbox.min.js"></script>
</head>
<body>
<script>
var animalsDict = {
Dog: validateDogSound(),//Cat: validateCatSound(),//Bird: ... etc
}
function validateDogSound(){
bootbox.alert("dogs bark!");
return false;
}
console.log('testDog',animalsDict["Dog"]);
</script>
</body>
</html>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。