当通过JS更新值时,jQuery对更改/输入不起作用

jQuery on change/input not working when updating value via JS

本文关键字:不起作用 输入 jQuery JS 更新      更新时间:2023-09-26

我注意到,当Javascript本身完成更改时,$('#firstId')的事件不会触发。

为什么会这样?

是否有方法仍然触发事件?

下面是一个例子:

$('#firstId').on('change input paste', function(){
  console.log("this is the input event being fired");
});
$('#randomButton').on('click', function(){
  $('#firstId').val(Math.floor(Math.random()*2147483647 )+1);
  console.log("randomButton being fired");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span for="firstId">number: </span>
<input type="number" id="firstId"/>
<p>Or</p>
<button id="randomButton">Get a random number</button><br>

这是因为上面通过处理程序附加的所有事件都是由用户操作触发的,而不是通过代码触发的。您可以在这里使用.trigger().change()来触发事件:

$('#firstId').val(Math.floor(Math.random()*2147483647 )+1).change();

$('#firstId').val(Math.floor(Math.random()*2147483647 )+1).trigger('change');