【发布时间】:2019-01-02 19:54:47
【问题描述】:
我一直在尝试创建一个按钮来再次调用函数以显示新的 HTML 段落,但由于某种原因它不会这样做。
我试图在我的 JS 文件中的按钮上调用函数,但是当我单击它时,该按钮没有任何改变。一切都保持不变。
这是在 HTML 的末尾,我在其中创建了按钮:
<p>“We labour at our daily work more ardently and thoughtlessly than is necessary to sustain our life because it is even more necessary not to have leisure to stop and think. Haste is universal because everyone is in flight from himself.”</p>
<p>“One should die proudly when it is no longer possible to live proudly.”</p>
</div>
<button class="button">Thus Spoke Nietzsche</button>
<script src="randomize.js"></script>
</body>
这是 JS:
"use strict";
const quotes = document.querySelectorAll("p");
const randomize = function() {
let num = (Math.floor(Math.random() * Math.floor(quotes.length)) - 1);
let quote = quotes.item(num).innerHTML;
return quote;
}
const run = function(){
let randomQuote = randomize();
let passage = document.getElementById('quotes');
passage.innerHTML = randomQuote;
return console.log(randomQuote);
}
const newQuote = document.querySelector('.button');
newQuote.addEventListener('click', run());
感谢您的帮助。
【问题讨论】:
-
应该是
newQuote.addEventListener('click', run);,在run之后没有()。您要传递对函数的引用,而不是调用函数的结果。
标签: javascript html dom button