Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/extjs/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 防止在页面加载时获取数据_Javascript - Fatal编程技术网

Javascript 防止在页面加载时获取数据

Javascript 防止在页面加载时获取数据,javascript,Javascript,这里是代码新手! 我正在创建一个报价生成器。我获取API并设法同步onclick=“get NewQuote”的按钮,但当我第一次加载页面时,它会在我没有单击按钮的情况下给我一个报价。如何使函数仅在单击按钮时运行,而不在浏览器中打开页面时加载页面时运行?谢谢大家! var getNewQuote = document.getElementById('btn'); getNewQuote.addEventListener("click", function() {

这里是代码新手! 我正在创建一个报价生成器。我获取API并设法同步onclick=“get NewQuote”的按钮,但当我第一次加载页面时,它会在我没有单击按钮的情况下给我一个报价。如何使函数仅在单击按钮时运行,而不在浏览器中打开页面时加载页面时运行?谢谢大家!

var getNewQuote = document.getElementById('btn');


getNewQuote.addEventListener("click", function() {
    location.reload();
    return false;
});


fetch('http://quotes.stormconsultancy.co.uk/random.json')
    .then((response) => {
        return response.json()
    })
    .then((data) => {
        // Work with JSON data here
        console.log(data);
        document.getElementById('quote').textContent = data.quote;
        document.getElementById('author').textContent = data.author;
    })
    .catch((error) => {
        console.log('error');
        console.error(error);
        document.getElementById('author').textContent = "Oops, seems like there's an error...Well, you can always grab a real book and find a quote. Sorry! ";
    });
这是我的按钮:

 <button type="submit" class="quote-btn" id="btn" onclick="getNewQuote()">NEW QUOTE</button>
新报价

将获取部分放在函数中,并随时调用它。 e、 g


然后
newquote

那么为什么提取代码不在addEventListener中呢????为什么要调用reload来获取?重新加载整个页面会破坏对动态内容使用fetch的功能
function myFetch(){
  fetch('http://quotes.stormconsultancy.co.uk/random.json')
  .then((response) => {
    return response.json()
  })
  .then((data) => {
    // Work with JSON data here
    console.log(data);
    document.getElementById('quote').textContent = data.quote;
    document.getElementById('author').textContent = data.author;
  })
  .catch((error) => {
    console.log('error');
    console.error(error);
    document.getElementById('author').textContent = "Oops, seems like there's 
   an error...Well, you can always grab a real book and find a quote. Sorry! 
  ";
  });
 }