通过JS更新值时,更改/输入的jQuery无法正常工作

Kev*_*oet 4 javascript jquery javascript-events jquery-on

我注意到$('#firstId')当javascript本身完成更改时,事件没有触发.

这是为什么?

还有办法让事件发生吗?

这是一个例子:

$('#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");
});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

Mil*_*war 11

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

$('#firstId').val(Math.floor(Math.random()*2147483647 )+1).change();
Run Code Online (Sandbox Code Playgroud)

要么

$('#firstId').val(Math.floor(Math.random()*2147483647 )+1).trigger('change');
Run Code Online (Sandbox Code Playgroud)