javascript - 我不知道如何将用户的输入附加到 Javascript 中的数组中

标签 javascript html arrays input user-input

我正在做一项作业,我需要创建 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/

相关文章:

javascript - 结构中的 samplerCube 导致 GL_INVALID_OPERATION

html - 在 HTML 步进器中显示单位 &lt;input type ="number">

c - 将指针与 union 、数组和函数一起使用

c - 将 String 解析为 C 中的标记 - 出了什么问题?

javascript - !variable 在 javascript 中不起作用

javascript - 如何将数据从 module.export 函数传递到对象

javascript - Kendo Ui Chart - 如何知道图表已完成加载?

java - 如何使用 JavaMail 发送 html 电子邮件?

javascript - 如何在我的页面中为左侧菜单添加不同的滚动条

php - 将包含字符串和数字的多维数组插入 MySQL