您可以尝试使用它来获取更改时的字符串:
<form>
<input type="text" name="password" value="" id="password" />
</form>
<div id="result"></div>
// Here myString is declared outside event listener so it can be used to store data.
let myString = "";
// This will be executed only on input changes.
document.getElementById("password").addEventListener('input', (event) => {
// Store string value
myString = event.srcElement.value;
// this will log string value
console.log(myString);
// or
logPassword();
// output value in another html tag
document.getElementById("result").innerHTML = myString;
});
// This will log empty string because myString = ""
// This code is executed at start like it is
console.log(myString);
// An example of function that can be create to access myString
function logPassword() {
console.log(myString);
}
Mozilla input event
编辑:使用按钮的解决方案
注意:不提交东西就不需要form标签。
<form>
<input type="text" name="password" value="" id="password" />
<!-- Pass the input password value to the write function -->
<button onclick="writeText(document.getElemenById('password').value)" id="bocken">ok.</button>
</form>
<div id="result"></div>
// Pass the string (submitted password)
function writeText(myString){
document.getElementById("result").innerHTML = myString;
}
通过等待 DOM 准备好更好地使用 javascript
// All code inside will be executed only when the page is loaded and ready to use.
document.addEventListener("DOMContentLoaded", function(event) {
// do work
function writeText(myString){
document.getElementById("result").innerHTML = myString;
}
});
<input type="text" name="password" value="" id="password" />
<button id="bocken">ok.</button>
</form>
<div id="result"></div>
// All code inside will be executed only when the page is loaded and ready to use.
document.addEventListener("DOMContentLoaded", function(event) {
// This will be executed only on button click event.
document.getElementById("bocken").addEventListener('click', (event) => {
// output value in another html tag
document.getElementById("result").innerHTML = document.getElemenById('password').value;
});
});