我正在尝试学习 JavaScript,但由于通过多个函数使用变量而遇到了障碍。
浏览文档和 stackoverflow 投票最多的答案后,涉及全局变量以及如何通过多个函数有效地使用它们。
我几乎没有找到简单的解决方案。
有哪位好心人能够纠正这段完整的代码如何正常工作吗?
variable "ttl" and "msg" are needed to be passed from "ajax" function to "notify" function
<script src="js/jquery.js"></script>
<script src="js/bootstrap-notify.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// Global variables ttl and msg needed ?
var ttl = null;
var msg = null;
// Make an ajax call to json file.
$.ajax({
url: "lastorder.json",
dataType: "json",
// Parse title and message from json.
success: function(data) {
ttl = data.title;
msg = data.message;
}
});
// Notify function displays a title and message that was parsed from json file
$.notify({
icon: 'img/avatar.jpg',
title: ttl,
message: msg
},{
type: 'minimalist',
delay: 3000,
icon_type: 'image',
template: '<div data-notify="container" class="col-xs-11 col-sm-3 alert alert-{0}" role="alert">' +
'<img data-notify="icon" class="img-circle pull-left">' +
'<span data-notify="title">{1}</span>' +
'<span data-notify="message">{2}</span>' +
'</div>'
});
});
</script>
最佳答案
如果你想尝试@MikeC解决方案:
$(document).ready(function () {
// Global variables ttl and msg needed ?
var ttl = null;
var msg = null;
// Notify function displays a title and message that was parsed from json file
function notify(data) {
ttl = data.title;
msg = data.message;
$.notify({
icon: 'img/avatar.jpg',
title: ttl,
message: msg
}, {
type: 'minimalist',
delay: 3000,
icon_type: 'image',
template: '<div data-notify="container" class="col-xs-11 col-sm-3 alert alert-{0}" role="alert">' +
'<img data-notify="icon" class="img-circle pull-left">' +
'<span data-notify="title">{1}</span>' +
'<span data-notify="message">{2}</span>' +
'</div>'
});
}
// Make an ajax call to json file.
$.ajax({
url: "lastorder.json",
dataType: "json",
// Parse title and message from json.
success: notify
});
});
关于Javascript全局变量简单解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36799241/