我有一个 js 文件,其中声明了一个我想在 html 脚本中使用的变量
js 文件(controllerB.js)
var modalArticles = [];
$(document).ready(function () {
$.ajax({
url: "https://newsapi.org/v1/articles?source=google-news&sortBy=top&apiKey=*****"
}).then(function (data) {
modalArticles = data.articles;
})
})
html 文件
<head>
<meta charset="utf-8" />
<title>News</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="js/handlebars-v4.0.10.js"></script>
<script type="text/javascript" src="js/controllerB.js"></script>
</head>
<body></body>
<script type="text/javascript">
console.log('print: ' + modalArticles);
</script>
html 中 modalArticles 为空
最佳答案
您的变量为空,因为它仅在加载文档时才初始化。 您使用异步请求填充该变量,因此只有在 Promise 得到解析时它才可用。
如果你想在你的HTML中显示你的变量的内容,你可以使用jquery(根据你的标签)来设置你想要它显示的元素的HTML,以设置在then
方法。
如果你想让它显示在“#mydiv”中,你可以这样做:
.then(function(value){
$('#mydiv').html(value);
})
关于javascript - 在html文件上访问js文件的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44287034/