javascript - 使用 getElementById 更改 html 内容

标签 javascript html forms if-statement

好吧,所以我最近开始学习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。

大家有什么想法吗?这看起来像是一件愚蠢的小事。

最佳答案

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

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

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

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

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

最后,您还没有为任何元素指定 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>

关于javascript - 使用 getElementById 更改 html 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50778891/

相关文章:

javascript - 如何在javascript中的段落中附加数组中的文本?

javascript - Android Nexus 7 (HLS) 上的空 HTML5 视频持续时间

C# 形式 : progressbar doesn't show updates from thread doing work

javascript - 如果 URL 更改,则重定向页面返回

javascript - 如何从sql中获取nodejs的数据并返回json?

python - Python 处理的输出的最佳数据结构是什么?

forms - Angular 将选择值转换为 int

javascript - 提交 javascript 表单但数据未正确传递

javascript - 如何获取浏览器 "Document Mode"

Javascript Ajax 重新加载 Div