今天我尝试使用数组和对象在 JavaScript 中制作字典
我正在尝试使用提示在这里进行搜索
<html>
<body style="font-size: 40px">
<input type="text" id="myin">
<button id="btn">Search</button>
<div id="outputArea"></div>
<script>
var outputAreaRef = document.getElementById("outputArea");
var output = "";
var word = prompt("Enter something: ");
var acronyms = [{
acronym: "omg",
meaning: "Oh MY God"
},
{
acronym: "lol",
meaning: "Laugh Out Loud"
},
{
acronym: "lmao",
meaning: "Laughing My Age Off"
},
{
acronym: "wtf",
meaning: "What This Function"
}
];
for (var i = 0; i < acronyms.length; i++) {
if (acronyms[i].acronym === word) {
word = acronyms[i].meaning;
outputAreaRef.innerHTML = word;
}
}
</script>
</body>
</html>
但是当尝试使用具有 onclick 按钮功能而不是提示的输入元素时,它根本不起作用
这是带有输入和按钮的代码
<html>
<body style="font-size: 40px">
<input type="text" id="myin">
<button id="btn">Search</button>
<div id="outputArea"></div>
<script>
var outputAreaRef = document.getElementById("outputArea");
var output = "";
var word = document.getElementById("myin");
var acronyms = [{
acronym: "omg",
meaning: "Oh MY God"
},
{
acronym: "lol",
meaning: "Laugh Out Loud"
},
{
acronym: "lmao",
meaning: "Laughing My Age Off"
},
{
acronym: "wtf",
meaning: "What This Function"
}
];
for (var i = 0; i < acronyms.length; i++) {
if (acronyms[i].acronym === word) {
word = acronyms[i].meaning;
document.getElementById('btn').onclick = function() {
outputAreaRef.innerHTML = word;
}
}
}
</script>
</body>
</html>
请帮忙看看哪里错了
抱歉我的英语不好,
最佳答案
您的代码会立即执行,并且该单词尚未设置。因此什么也没有发生。
您必须将所有查找逻辑(获取当前输入并检查字典)移至 onclick
回调中。
关于javascript - 尝试使用数组和对象在 JavaScript 中创建字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52041717/