使用 Javascript 显示输入(来自 HTML)的特定输出

To display specific output for an input (from HTML) using Javascript

我刚开始使用 JavaScript 并想构建一个接受输入的 HTML 页面,而 JavaScript 从 HTML 获取输入并搜索数据库数组并显示每个输入的特定输出。 这是 HTML :

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>My Webpage!</title>
  </head>
  <body>
    <br><br><br><br>
    <input type="text" name="inputField" id="answer" placeholder="Enter the answer..." required>
    <button type="button" name="button" onclick="mySubmit()">Submit</button>
    <p id="demo"></p>
    <link href'./script.js">

</body>
</html>

这是 JavaScript:

var getInput = document.getElementById("answer").innertext;
console.log(getInput);
function mySubmit() {
    var text;
    var database = [
        {answer: "Apple", clue: "Steve Jobs"},
        {answer: "Mango", clue: "Fruit"}
    ];
    for(var i=0;i<database.length;i++){
        if(database[i].answer === getInput){
            text = database[i].clue;
            console.log(text);
        }
        else{
            text = "The answer is incorrect";
            console.log(text);
        }
        document.getElementById("demo").innertext = text;
    }
}

如果要求用户输入,代码应该按照Apple 并在 HTML 上给出输出 "Steve Jobs"。

有几处不正确,但总的来说您的代码差不多了。

首先你要找的 'innertext' 实际上是 'innerText'.
其次,输入元素没有 innerText。他们有一个属性 'value' 相反。
第三,要包含 javascript,您需要使用脚本标签而不是 link 标签。

此外,我更改了您的函数的绑定,并在 javascript 中使用 .addEventListener("click", ...) 而不是在您的 HTML 中执行此操作。但这几乎是偏好。大多数情况下,它会导致更少的错误,因为如果根本没有加载脚本,它就不会尝试查找指定的函数。

HTML

<!DOCTYPE html>
<html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title>My Webpage!</title>
    </head>
    <body>
        <br><br><br><br>
        <input type="text" name="inputField" id="answer" placeholder="Enter the answer..." required>
        <button id="submit" type="button" name="button">Submit</button>
        <p id="demo"></p>
        <script type="text/javascript" src="./script.js">
    </body>
</html>

脚本

function getInput() {
    return document.getElementById("answer").value;
}

var submitButton = document.getElementById("submit").addEventListener("click", mySubmit);

function mySubmit() {
    var text;
    var database = [
        {answer: "Apple", clue: "Steve Jobs"},
        {answer: "Mango", clue: "Fruit"}
    ];
    for(var i=0;i<database.length;i++){
        if(database[i].answer === getInput()){
            text = database[i].clue;
            console.log(text);
        }
    }

    if(!text) {
        text = "The answer is incorrect";
    }

    document.getElementById("demo").innerText = text;
}

你的代码有一些错误,让我试着解释一下你应该改用什么:

  • 要获取用户在 input 元素中键入的内容,您应该使用 value 属性而不是 innerText 属性。

Node.innerText is a property that represents the "rendered" text content of a node and its descendants. As a getter, it approximates the text the user would get if they highlighted the contents of the element with the cursor and then copied to the clipboard. - innerText MDN article.

  • 至get/set 元素内的文本(inputs 除外),您应该使用textContent 属性。 textContent MDN article
  • 要在网页中附加脚本文件,您应该使用 script 标签,方法是将文件路径放入 script 标签的 src 属性中:<script src="path/to/javascript/file.js"></script>
  • 尽量避免使用内联事件侦听器,而应该使用 addEventListener 方法。

这是一个可运行的片段来说明所说的所有内容:

// create reference to the input and the p#demo to get them when we need them
var btn = document.getElementById('btn'),
  demo = document.getElementById('demo');
// add event listener to the button
btn.addEventListener('click', mySubmit);
// the event handler function
function mySubmit(e) {
  // prevent the default behaviour when the button is clicked
  e.preventDefault();
  // the value of the input must be fetched inside the event handler to get it every time the button is clicked
  var getInput = document.getElementById("answer").value.toLowerCase(),
    text = '',
    database = [{
      answer: "Apple",
      clue: "Steve Jobs"
    }, {
      answer: "Mango",
      clue: "Fruit"
    }],
    i = 0,
    l = database.length;
  for(; i < l; i++) {
    if(database[i].answer.toLowerCase() === getInput) {
      text = database[i].clue;
      break;
    }
  }
  if(text === '') {
    text = "The answer is incorrect";
  }
  demo.textContent = text;
}
    <input type="text" name="inputField" id="answer" placeholder="Enter the answer..." required>
    <button type="button" name="button" id="btn">Submit</button>
    <p id="demo"></p>

您可以使用 find 数组助手来查找与文本字段输入相匹配的对象。它会 return 根据您的需要为您提供对象。你可以在 MDN 上查看 find array helper 的文档。

HTML

<input type="text" name="inputField" id="answer" placeholder="Enter the answer...">
<button type="button" name="button" onclick="mySubmit()">Submit</button>
<p id="demo"></p>

脚本

function mySubmit() {
        let getInput = answer.value;
        var text;
        var database = [
            { answer: "Apple", clue: "Steve Jobs" },
            { answer: "Mango", clue: "Fruit" }
        ];
        text = database.find((data) => {
            if (data.answer === getInput) {
                return data;
            }
        });
        if (typeof text === 'object')
            text = text.clue;
        else
            text = "The answer is incorrect";
        demo.textContent = text;
    }

Find array helper - MDN