javascript - Javascript 或 Jquery 事件触发器 - 如何在 javascript 将值传递到输入框时触发事件
问题描述
javascript将值传递到输入框时如何触发事件
<!DOCTYPE html>
<html>
<body>
<p>Write something in the text field to trigger a function.</p>
<input type="text" id="myInput" oninput="myFunction()">
<p id="demo"></p>
<script>
document.getElementById("myInput").value = 100;
function myFunction() {
var x = document.getElementById("myInput").value;
document.getElementById("demo").innerHTML = "You wrote: " + x;
}
</script>
</body>
</html>
当值 100 自动生成时,应显示“You Wrote 100”
解决方案
我真的不知道你的问题,它在这里工作正常。JS 示例:
document.getElementById("myInput").value = 100;
function myFunction() {
var x = document.getElementById("myInput").value;
document.getElementById("demo").innerHTML = "You wrote: " + x;
}
<p>Write something in the text field to trigger a function.</p>
<input type="text" id="myInput" onkeyup="myFunction()">
<p id="demo">You wrote: 100</p>
jQuery 示例:
$('#myInput').val(100);
$('#myInput').keyup(function(){
$('#demo').html('You wrote: ' + $('#myInput').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Write something in the text field to trigger a function.</p>
<input type="text" id="myInput">
<p id="demo">You wrote: 100</p>
我建议您使用 onkeyup,因为它比 onchange 更具动态性。
推荐阅读
- google-chrome - Headless Chrome 在 IIS 下失败,但在命令行上工作
- python - 重复循环直到函数输入改变
- javascript - 使用变量检查字符串格式
- java - 为什么集合的输出与列表相同。我认为这会有所不同,因为集合是无序的
- html - 如何在 IE 中创建带有排水沟的 flex 行?
- spring-security - 错误 SAMLResponse 上的 Spring Security SAML 无限重试循环
- sql - 经典报告的 APEX 中未显示列标题
- react-native - 不变违规:文本字符串必须在
组件,在 React Native 中使用条件运算符时发生 - javascript - 如何在 XCUITest 自动化期间在移动 Safari 中注入/评估 javascript?
- javascript - 页面刷新时是否调用了 Vue 的“销毁”方法?