javascript - 创建 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>
解决方案
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>
推荐阅读
- laravel - Laravel 转换咨询 sql 一个 queryBuilder(Laravel)
- javascript - 如何设置 Jquery Toggle 默认显示或隐藏使用 html 类控件?
- android - 尝试使用 MutableLiveData 值时出现 NullPointerException
- php - Laravel 获取连接表的最新行
- awk - 如何将 YAML 拆分为具有正确名称的多个文件
- java - 为什么与布尔数组相比,位向量只能将空间使用量减少八倍?
- java - 反应式 java 将 Mono 对象转换为没有 block() 的对象;
- python - pandas:如何将字典转换为转置数据框?
- database - 如何查看雪花数据库的克隆属性
- matlab - 根据数值调整 fprintf 中的字符串格式