![](/img/trans.png)
[英]In JavaScript trying to create dictionary from 3 array objects - Challenge Question
[英]Trying to make dictionary in JavaScript using array and objects
今天,我嘗試制作嘗試使用數組和對象的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
回調中。
您需要使用document.getElementById("myin").value
獲取輸入的document.getElementById("myin").value
。其次,創建一個function
並將其附加到按鈕的單擊處理程序。
在此事件處理程序內獲取input
的值,在單擊處理程序外檢索該值將無法工作。
var outputAreaRef = document.getElementById("outputArea"); var output = ""; 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" } ]; //Attach event listener to the button document.getElementById('btn').addEventListener('click', searchWord) function searchWord() { // need to get the value of the input var word = document.getElementById("myin").value; // if matches then show the value for (var i = 0; i < acronyms.length; i++) { // to lowerCase to make it case insensitive & trim to remove white space if (acronyms[i].acronym === word.toLowerCase().trim()) { outputAreaRef.innerHTML = acronyms[i].meaning; } } }
body { font-size: 40px; }
<input type="text" id="myin"> <button id="btn">Search</button> <div id="outputArea"></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.