【问题标题】:Why is my function firing before the onclick is clicked?为什么我的函数在单击 onclick 之前触发?
【发布时间】:2021-05-01 05:40:20
【问题描述】:

这是我下面的代码。在单击按钮之前,我的 getQuote 一直在触发。它在页面加载时立即触发。这对我来说很奇怪,有什么想法吗?

function _(id) {
  return document.getElementById(id);
}
var html = "";
const newQuote = document.getElementById("submit");
const tweet = _("tweet-quote");
var tweetURL = "https://twitter.com/intent/tweet?hashtags=RonSwanson&text=";

newQuote.onclick = getQuote();

//Get Quote Function

function getQuote() {
  var ourRequest = new XMLHttpRequest();
  ourRequest.open('GET', 'https://ron-swanson-quotes.herokuapp.com/v2/quotes')
  ourRequest.onload = () => {
    var ourData = JSON.parse(ourRequest.responseText);
    quoteText = ourData[0];
    html = "<i class='fas fa-quote-left'></i>"
    html += ourData[0] + "<i class='fas fa-quote-right'></i>";
    html += "<br><br>" + "<p class='text-right'> -Ron Swanson</p>";
    _("quote").innerHTML = html;
    tweet.setAttribute('href', tweetURL + encodeURIComponent('"' + quoteText + '"') + encodeURIComponent("-Ron Swanson"));
  }
  ourRequest.send();
}

【问题讨论】:

    标签: javascript function onclick


    【解决方案1】:

    改变这个: newQuote.onclick = getQuote();

    对此: newQuote.onclick = getQuote;

    【讨论】:

    • 对此进行详细说明。函数被触发的原因是() 本质上意味着调用(或触发)这个函数。按照答案建议删除它们(newQuote.onclick = getQuote)是说将您的 getQuote 函数分配给 newQuote.onclick
    • 天哪!我不敢相信我一直都不知道这一点,非常感谢你们!
    猜你喜欢
    • 1970-01-01
    • 2014-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-16
    • 2023-01-17
    • 1970-01-01
    • 2017-02-13
    相关资源
    最近更新 更多