【发布时间】:2018-03-16 21:06:16
【问题描述】:
我正在尝试从单击事件侦听器中更改全局变量。但是,一旦单击按钮,变量就无法更改。这里的目标是更改获取请求的 URL。
// Default URL
var url = 'https://newsapi.org/v2/top-headlines?sources=bbc-news&Apikey123';
var req = new Request(url);
// Event Listener - Change URL
document.getElementById('btn').addEventListener('click', function() {
var url = 'https://newsapi.org/v2/top-headlines?sources=cnn&apiKey=Apikey123';
var req = new Request(url);
sendRequest();
})
// Fetch Data from API
function sendRequest() {
fetch(req)
.then(r => r.json())
.then(r => {
const container = document.getElementsByClassName('post-container')[0];
for(i = 0; i < 5 ; i++) {
// Create post elements
const post = document.createElement('div');
const postHeader = document.createElement('div');
const postBody = document.createElement('div');
// Set ID
post.id = 'post';
postHeader.id = 'post-header';
postBody.id = 'post-body';
// Append Elements
container.appendChild(post);
post.appendChild(postHeader);
post.appendChild(postBody);
// Post title data from array into div
let article = r.articles[i];
let title = article.title;
let content = article.description;
postHeader.innerHTML = title;
postBody.innerHTML = content;
}
console.log(container);
});
}
sendRequest();
【问题讨论】:
-
去掉
var url = 'https://newsapi.org/v2/top-headlines?sources=cnn&apiKey=Apikey123';中的var -
所有的答案都是好的,知道的好习惯。变量声明,无论它们出现在哪里,都会在执行任何代码之前进行处理。用 var 声明的变量的范围是它的当前执行上下文,它要么是封闭函数,要么是在任何函数之外声明的变量,是全局的。如果你重新声明一个 JavaScript 变量,它不会丢失它的值。 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
标签: javascript api variables events fetch