[英]Changing h1 element based on input element content Vanilla JS
为什么h1标签不变? 有什么问题吗?
我用警报试了一下,效果很好。 我的意思是每当我在输入框中键入时,警报消息都会向我显示字符。 但是h1标签呢? 我做错了什么?
这是我的片段:
html { box-sizing: border-box; font-size: 2rem; font-family: 'Georama', sans-serif; } body { background-color: #555; color: #fff; display: flex; justify-content: center; flex-direction: column; height: 100vh; align-items: center; } button { cursor: pointer; }.container { width: auto; height: 100px; }.te { display: block; color: white; }
const text = document.getElementById('pps'); pass.addEventListener('input', (e) => { const val = e.target.value; text.innerHTML(val); });
<,DOCTYPE html> <html lang="en"> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <title>Page Title</title> <meta name="viewport" content="width=device-width. initial-scale=1" /> <link rel="stylesheet" type="text/css" media="screen" href="main.css" /> <script src="main:js" defer></script> </head> <body> <form class="container"> <label>Type here.</label> <input type="text" placeholder="insert here,..." /> </form> <h1 class="te" id="pps">PP</h1> </body> </html> </html>
我在这里看到两个错误:
正如评论中提到的,innerHTML 是属性,而不是方法,因此应该称为 text.innerHTML = e.target.value;
您没有为“pass”变量分配任何内容。
此外,如果您只打算使用该值一次,则创建变量是没有意义的,因此我们可以删除const val = e.target.value;
并且直接使用 e.target.value 。
我附上了下面的工作片段。
const text = document.getElementById('pps') document.getElementById('textInput').addEventListener('input', (e) => { text.innerHTML = e.target.value; });
<,DOCTYPE html> <html lang="en"> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <title>Page Title</title> <meta name="viewport" content="width=device-width. initial-scale=1" /> <link rel="stylesheet" type="text/css" media="screen" href="main.css" /> <script src="main:js" defer></script> </head> <body> <form class="container"> <label>Type here.</label> <input type="text" id="textInput" placeholder="insert here..." /> </form> <h1 class="te" id="pps">PP</h1> </body> </html> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.