首页 > 解决方案 > 使用 getElementById 更改 html 内容

问题描述

好的,所以我最近开始学习html/css和js。在多个教程中,我无法弄清楚如何正确使用 getElementById 函数。

<!DOCTYPE html>
<html>
<head>
    <title>Practice</title>
    <link rel="stylesheet" href="stylesheet.css" />
</head>
<body>
    <h1 id="first">My Practice Page!</h1>

    <form name="myForm" onsubmit="return validateForm()"
    <label>Name:</label><br />
    <input type="text" name="fname" />
    <input type="submit" value="Submit" />
    </form>

    <script>
        var nm = document.forms["myForm"]["fname"].value;
        if (nm == "Don") {
            document.write("Hi, Don");
            return true;
        }
        else {
            document.write("Hi, stranger.");
            return false;
        }
    </script>
</body>
</html>

提交按钮工作并注册 fname 等于输入文本,但它要么没有将该值分配给 nm,要么我没有正确使用 document.write。

有人有想法么?这似乎将是一件愚蠢的小事。

标签: javascripthtmlformsif-statement

解决方案


首先,您的元素在开始标记的末尾<form>没有符号。>

接下来,您的脚本会在页面加载后立即运行,此时用户还没有机会在该字段中输入任何内容。

接下来,document.write不应在这种情况下使用,因为它会覆盖现有文档。相反,设置一个空元素,您将在其中写入输出。

此外,由于您实际上并没有在任何地方提交表单数据,因此不要使用提交按钮和submit事件。只需使用常规按钮及其click事件。

而且,不要使用内联 HTML 事件属性 ( onsubmit)。相反,请在 JavaScript 中设置您的事件处理程序。

最后,你没有给任何元素 an id,所以你不能用它.getElementById()来找到任何元素。

<!DOCTYPE html>
<html>
<head>
    <title>Practice</title>
    <link rel="stylesheet" href="stylesheet.css">
</head>
<body>
    <h1 id="first">My Practice Page!</h1>

    <form name="myForm">
      <label>Name:</label><br>
      <input type="text" name="fname" id="fname">
      <!-- Use a regular button since you aren't submitting form data anywhere -->
      <input type="button" value="Submit">
    </form>
    
    <div id="output"></div>
    <script>
      // Set up a click event handler for the button
      document.querySelector("[type='button']").addEventListener("click", validateForm);
      
      // Get the reference to your text field. You can't get it by its id unless you've
      // given it an id. name is not the same thing as id.
      var fName = document.getElementById("fname");
      
      // You didn't have your code inside of the callback function
      function validateForm(){

        if (fName.value == "Don") {
            // Just populate a pre-existing element with the correct data.
            output.textContent = "Hi, Don";
        }
        else {
            output.textContent = "Hi, stranger.";
        }
      }
    </script>
</body>
</html>


推荐阅读