当我在某些文件中编写代码时(例如:test.html):
<html>
<head>
<title>Test</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$.getJSON('https://newsapi.org/v1/articles?source=techcrunch&sortBy=top&apiKey=my-api-key',function(json) {
console.log(json);
});
</script>
</body>
</html>
但是如果我在其他文件中执行相同的操作,请说(main.js)
(function(){
$.getJSON('https://newsapi.org/v1/articles?source=techcrunch&sortBy=top&apiKey=my-api-key',function(json) {
console.log(json);
});
});
上面的代码在控制台中未显示任何JSON数据,我在HTML中添加了main.js。
最佳答案
因为在第二个代码段中,该功能根本不执行。
下面的代码
(function(){
$.getJSON('... url ...', function(json) {
console.log(json);
};
});
可以简化成
(function(){});
哪个根本不执行。您需要将括号放在函数的末尾才能执行,如下所示:
(function(){}());
或者更好的方法是,在页面加载后,使用jquery document ready速记版正确执行。
$(function(){});
希望对您有所帮助。