【问题标题】:Change Fetch URL from event listener?从事件侦听器更改获取 URL?
【发布时间】: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&amp;apiKey=Apikey123';中的var
  • 所有的答案都是好的,知道的好习惯。变量声明,无论它们出现在哪里,都会在执行任何代码之前进行处理。用 var 声明的变量的范围是它的当前执行上下文,它要么是封闭函数,要么是在任何函数之外声明的变量,是全局的。如果你重新声明一个 JavaScript 变量,它不会丢失它的值。 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

标签: javascript api variables events fetch


【解决方案1】:

解决问题:

...
    document.getElementById('btn').addEventListener('click', function() {
      var url = 'https://newsapi.org/v2/top-headlines?sources=cnn&apiKey=Apikey123';
      // Don't use var, becouse it's variable have scope in current function
      // var req = new Request(url);
      req = new Request(url);
      sendRequest();
    })
...

但最好将参数发送到sendRequest:

...
    // 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(req); // <--- set param
    })

    // Fetch Data from API
    function sendRequest(req) { // <--- get param
      ...
    });
...

【讨论】:

    【解决方案2】:

    从事件监听器中移除变量

     document.getElementById('btn').addEventListener('click', function() 
    {
      url = 'https://newsapi.org/v2/top-headlines?sources=cnn&apiKey=Apikey123';
      var req = new Request(url);
      sendRequest();
    })
    

    【讨论】:

      【解决方案3】:

      问题是你声明了两次 var url 和两次 var req 第一个在代码开头,第二个在事件监听器中,

      试试这个

      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() {
       url = 'https://newsapi.org/v2/top-headlines?sources=cnn&apiKey=Apikey123';
         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();
      

      【讨论】:

        猜你喜欢
        • 2014-01-07
        • 2018-06-03
        • 1970-01-01
        • 2011-01-11
        • 1970-01-01
        • 2020-12-14
        • 2020-09-06
        • 2021-10-19
        • 1970-01-01
        相关资源
        最近更新 更多