首页 > 解决方案 > 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”

标签: javascriptjquery

解决方案


我真的不知道你的问题,它在这里工作正常。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 更具动态性。


推荐阅读