使用jQuery模拟按键并触发输入

时间:2017-08-21 07:56:23

标签: javascript jquery triggers

Reacts TestUtils.simulate也会导致oninput函数触发。但是,由于某些限制,我无法使用它。

有没有办法模拟,从而导致oninput函数触发,使用jQuery的kerypress?

1 个答案:

答案 0 :(得分:0)

你的意思是这样吗?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset>
<label for="target">Type Something:</label>
<input id="target" type="text">
</fieldset>
</form>
<button id="other">
 Trigger the handler
</button>
  <script src="/resources/events.js"></script>

  <script>
   var xTriggered = 0;
   $( "#target" ).keypress(function( event ) {
   if ( event.which == 13 ) {
   event.preventDefault();
     }
   xTriggered++;
  var msg = "Handler for .keypress() called " + xTriggered + " time(s).";
  console.log( msg, "html" );
  console.log( event );
 });

 $( "#other" ).click(function() {
 $( "#target" ).keypress();
 });
</script>