我正在做一项作业,我需要创建 javascript 代码以允许用户输入内容并将其附加到数组中。这是 HTML:
<html lang="en">
<head>
<title>Magic 8 Ball!</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container">
<h1>Magic 8 ball</h1>
<h2>Ask your question, then click on the button!</h2>
<div class="eightBall">
<div id="output">
<p id="result">8</p>
</div>
</div>
<div class="inpBox">
<input type="text" id="inputBox"></input>
</div>
<div class="buttons">
<button id = "addButton" type="button">Add</button>
<button type="button">Custom</button>
<button id = "defaultButton" type="button">Default</button>
<button id = "Ask" type="button">Ask</button>
</div>
</div>
</body>
<script src="js/main.js"></script>
</html>
和 Javascript:
console.log(defaultList)
var customList = [""]
var inputText = document.getElementById("inputBox")
console.log(customList);
document.getElementById("addButton").addEventListener("click", function(){
customList.push(inputText);
console.log(customList);
});
除了当我检查控制台日志以查看 customList 的值时,一切都正常工作,它带来了实际的输入框本身而不是其中的文本。 控制台日志的图像: https://imgur.com/a/AiV4hRM 我只需要用户输入一些我将附加到空数组的文本。它不接受用户输入的文本,而是接受实际的输入框。
最佳答案
您需要从 value
属性中获取输入的值。
下面的代码将只返回对输入的引用而不是值。
var inputText = document.getElementById("inputBox");
要获取 input
的值,您需要从 value 属性中获取它。
var inputText = document.getElementById("inputBox");
console.log(inputText.value);
工作示例:
let customList = []
let inputText = document.getElementById("inputBox")
console.log(customList);
document.getElementById("addButton").addEventListener("click", function() {
let inputValue = inputText.value;
if (inputValue) {
customList.push(inputValue);
console.log(customList);
}
});
<input type="text" id="inputBox">
<button type="button" id="addButton">Click me</button>
关于javascript - 我不知道如何将用户的输入附加到 Javascript 中的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60593628/