为什么我的函数在单击 onclick 之前触发?
Why is my function firing before the onclick is clicked?
下面是我的代码。在单击按钮之前,我的 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();
}
改变这个:
newQuote.onclick = getQuote();
对此:
newQuote.onclick = 获取报价单;
下面是我的代码。在单击按钮之前,我的 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();
}
改变这个: newQuote.onclick = getQuote();
对此: newQuote.onclick = 获取报价单;