无法获取按钮以连接到javascript代码



我是JavaScript的新手,我正在制作一个随机报价生成器,但我似乎无法让我的js代码链接到按钮。这和我的选择器有关吗?

let quotes = ['The greatest glory in living lies not in never falling, but in rising every time we fall.', 'The way to get started is to quit talking and begin doing.', 'If life were predictable it would cease to be life, and be without flavor.', 'Life is what happens when youre busy making other plans.', 'Spread love everywhere you go. Let no one ever come to you without leaving happier.'];
let author = ['Nelson Mandela', 'Walt Disney', 'Eleanor Roosevelt', 'John Lennon', 'Mother Teresa'];
const quoteId = document.querySelector('.quote');
const authorId = document.querySelector('.source');
const btn = document.getElementById('loadQuote');

btn.addEventListener('click', function() {
quote.textContent = quotes[randomNum()];
source.textContent = author[randomNum()];
});

function randomNum() {
Math.floor(Math.random() * quotes.length)
};
<div id="quote-box">
<p class="quote">You can do anything but not everything</p>
<p class="source">David Allen<span class="citation">Making It All Work</span><span class="year">2009</span></p>
</div>
<button id="loadQuote">Show another quote</button>
</div>

有不同的错误:

在命名函数中,你应该明确地写"return"函数

返回的内容假设"quote"one_answers";author"按位置进行配对,则应使用常见的"randNum"在事件侦听器中传递的函数中,

其他类型错误修复。

let quotes = [
"The greatest glory in living lies not in never falling, but in rising every time we fall.",
"The way to get started is to quit talking and begin doing.",
"If life were predictable it would cease to be life, and be without flavor.",
"Life is what happens when youre busy making other plans.",
"Spread love everywhere you go. Let no one ever come to you without leaving happier.",
];
let author = [
"Nelson Mandela",
"Walt Disney",
"Eleanor Roosevelt",
"John Lennon",
"Mother Teresa",
];
const quoteId = document.querySelector(".quote");
const authorId = document.querySelector(".source");
const btn = document.getElementById("loadQuote");
btn.addEventListener("click", function () {
let randNum = randomNum();
quoteId.textContent = quotes[randNum];
authorId.textContent = author[randNum];
});
function randomNum() {
return Math.floor(Math.random() * quotes.length);
}

我过去曾多次遇到过这个问题。您可以执行以下两种操作之一:

可以将btn.addEventListener('click', ...)改为btn.onclick = function() { ... }

或者将btn.addEventListener('click', ...)改为btn.addEventListener('onclick')

发生这种情况是因为'click'函数运行,因为它是button元素的查询。想象一下,它就像在按钮元素中,你会在那里做<button onclick="myFunction()"></button>

相关内容

  • 没有找到相关文章

最新更新