javascript - 使用 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。
有人有想法么?这似乎将是一件愚蠢的小事。
解决方案
首先,您的元素在开始标记的末尾<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>
推荐阅读
- python - 如何使用python输出特定列的前5个以及相关列?
- python - 如何检查列表/元组中的某些值是否相等?
- spring-boot - Spring Boot 应用程序无法连接到 kubernetes 集群上的 RabbitMQ
- java - fat-JAR 文件的外部化配置设置
- node.js - 使用服务器端的 nodeJS 和客户端的 Angular 连接到远程领域,好习惯吗?
- android - 使用 Android Jetpack 导航时,片段视图状态未在后按时保存
- c# - Asp.Net 中使用的加密是什么?
- rspec - 使用 RSpec,我可以指定记录的故障吗?
- python - Beautiful Soup,for循环写入数据
- vb.net - 在 VB.net 中返回 tic