[英]h1 innerHTML value doesn't display form submission value correctly
I am new to JavaScript. I am trying to change my h1 tag value in HTML to a value based on form submitted.我是 JavaScript 的新手。我正在尝试将 HTML 中的 h1 标签值更改为基于提交的表单的值。 However, it displays only for a split second before disappearing.
但是,它只显示一瞬间就消失了。 I would like to display the value permanently.
我想永久显示该值。 Your advice is appreciated.
感谢您的建议。 Thank you.
谢谢你。
The greeting was displayed only for a split second.问候语只出现了一瞬间。 I would like it to be displayed permanently.
我希望它永久显示。 I suspect the issue is in the triggering of the event listener in JS code.
我怀疑问题在于 JS 代码中事件侦听器的触发。
>! >! HTML code
HTML代码
<!DOCTYPE html>
<html lang="en">
<head>
<title>Count</title>
<script src="counter.js"></script>
</head>
<body>
<h1>Cold</h1>
<form>
<input autofocus id="name" placeholder="Name" type="text">
<input type="submit">
</form>
</body>
</html>
>! >! JS code
JS代码
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('form').onsubmit = function() {
const name = document.querySelector('#name').value;
document.querySelector('h1').innerHTML = `Hello ${name}`;
};
});
You have to add the preventDefault property to the event, so it does not refresh the page onSubmit:您必须将 preventDefault 属性添加到事件中,这样它就不会在提交时刷新页面:
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('form').onsubmit = function(event) {
const name = document.querySelector('#name').value;
event.preventDefault();
document.querySelector('h1').innerHTML = `Hello ${name}`;
};
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.