首页 > 解决方案 > 创建 onclick 按钮事件时遇到问题

问题描述

我正在尝试使用在 js 中运行此脚本的按钮创建一个非常简单的网页。我有一个 js 文件和一个 html 文件。

//var button = document.querySelector("button")

//button.onclick = function() {
demo = function() {
    const CambDict = require("camb-dict");
    const dictionary = new CambDict.Dictionary();
    let lexicon = ["Flâneur", "Shibboleth", "Farrow", "Bon viveur/vivant"]
    let randLexicon = lexicon[Math.floor(Math.random() * lexicon.length)]
    console.log(randLexicon)

    dictionary.meaning(randLexicon)
        .then(console.log)
        .catch(console.error)
}
<!DOCTYPE html>
<html>
  <head>
    <title>Dictionary</title>
  </head> 
  <body>
    <h1>Simple Dictionary</h1>
    <button onclick="myFunction()">New word</button>
    <p id="demo"></p>
    <script src="dictionary.js"> function myFunction() </script>
  </body>
</html>

标签: javascripthtmlbuttononclick

解决方案


function myFunction () {
    const CambDict = require("camb-dict");
    const dictionary = new CambDict.Dictionary();
 let lexicon = ["Flâneur", "Shibboleth", "Farrow", "Bon viveur/vivant"]
    let randLexicon = lexicon[Math.floor(Math.random() * lexicon.length)]
    console.log(randLexicon)

    dictionary.meaning(randLexicon)
        .then(console.log)
        .catch(console.error)
}
<!DOCTYPE html>
<html>
  <head>
    <title>Dictionary</title>
  </head> 
  <body>
    <h1>Simple Dictionary</h1>
    <button onclick="myFunction()">New word</button>
    <p id="demo"></p>
  </body>
</html>


推荐阅读