【问题标题】:Why is my button not calling the function again?为什么我的按钮不再调用该函数?
【发布时间】:2019-01-02 19:54:47
【问题描述】:

我一直在尝试创建一个按钮来再次调用函数以显示新的 HTML 段落,但由于某种原因它不会这样做。

我试图在我的 JS 文件中的按钮上调用函数,但是当我单击它时,该按钮没有任何改变。一切都保持不变。

这是在 HTML 的末尾,我在其中创建了按钮:

<p>&#8220;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.&#8221;</p>
<p>&#8220;One should die proudly when it is no longer possible to live proudly.&#8221;</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


【解决方案1】:

所以至少部分问题是这样的:

newQuote.addEventListener('click', run());

应该只是:

newQuote.addEventListener('click', run);

addEventListener 期望您给它的第二个参数是一个函数。这将是它在单击 newQuote 时执行的功能。但是,当您说 run() (带括号)时,您实际上是在 invoking run 函数并将结果提供给 addEventListener ,其中case 将是undefined

可能还有更多问题,但我没有时间真正创建一个代码笔并彻底检查它,但这是我最感兴趣的第一件事。

【讨论】:

    猜你喜欢
    • 2020-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-07
    • 2016-01-27
    相关资源
    最近更新 更多