繁体   English   中英

当用户键入输入标记时,会运行常量函数

[英]Constant function run when user typing into input tag

我想知道如何在每次删除文本时运行TextEdit函数。 目前,只有在我对输入标签失去焦点时才会更新。

 function textEdit(e) { document.getElementById("outputTxtBtn").innerHTML = e.value; } 
 <input type="text" name="title" id="inputTxtBtn" value="About me" onblur="textEdit(this)" /> <a title="About me" id="outputTxtBtn" href="#">About Me</a> 

使用oninput侦听任何类型的值修改

 function textEdit(e) { document.getElementById("outputTxtBtn").innerHTML = e.value; } 
 <input type="text" name="title" id="inputTxtBtn" value="About me" oninput="textEdit(this)" /> <a title="About me" id="outputTxtBtn" href="#">About Me</a> 

为防止不需要的脚本注入,请使用textContent而不是innerHTML
为了保持JS包含良好且易于调试 - 从HTML标记中删除内联JS

 function textEdit() { document.querySelector(this.getAttribute("data-textedit")).textContent = this.value; } [...document.querySelectorAll("[data-textedit]")].forEach(el => el.addEventListener("input", textEdit) ); 
 <input data-textedit="#outputTxtBtn" type="text" name="title" value="About me"> <a id="outputTxtBtn" href="#!">About me</a><br> <input data-textedit="#test" type="text" name="title" value="Lorem"> <p id="test" href="#!">Lorem</p> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM