jQuery触发按下输入不起作用

时间:2017-02-01 18:53:28

标签: javascript jquery

这是我的剧本:

$('.target input').val('my value');
$('.target input').trigger(jQuery.Event('keypress', { keycode: 13 }));

第一行工作正常,值设置正确,然后我需要按输入元素,但第二行不起作用。我的意思是事件未被解雇:

$('.target input').keyup(function(e){
      if(e.keyCode == 13)
      {
            alert($(this).val());
      }
 });

当我手动按Enter键时,事件会触发,但是javascript事件未触发。问题出在哪里?

4 个答案:

答案 0 :(得分:2)

您需要触发keyup事件才能触发keyup事件处理程序。虽然属性keycode应更改为keyCode,因为对象属性区分大小写Javascript。

$('.target input').trigger(jQuery.Event('keyup', { keyCode: 13 }));

$('.target input').keyup(function(e) {
  if (e.keyCode == 13) {
    alert($(this).val());
  }
});

$('.target input').val('my value');
$('.target input').trigger(jQuery.Event('keyup', {
  keyCode: 13
}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="target">
  <input/>
</div>

FYI:您需要在事件触发前使用代码绑定事件处理程序,否则它将不会侦听在连接侦听器之前触发的事件。

虽然传递jQuery.Event的对象属性支持1.6以上,但请检查您的jQuery版本。

  

从jQuery 1.6开始,您还可以将对象传递给jQuery.Event(),并在新创建的Event对象上设置其属性。

答案 1 :(得分:0)

var e = jQuery.Event("keydown");
e.which = 13;
$(".target input").trigger(e);

答案 2 :(得分:0)

这应该为你做的工作,

  var e = jQuery.Event("keypress");
    e.which = 13; //choose the one you want
    e.keyCode = 13;
    $("#theInputToTest").trigger(e);

答案 3 :(得分:0)

<强> is_attachment()

基本上你需要像我在小提琴中那样触发keyup事件。

<强> HTML

<input type=text />

<强> JS

$(":input").keyup(function(e){
  if(e.which==13){
    alert("Fired");
  }
});

$(":input").val("TEST");
$(":input").trigger($.Event("keyup",{which:13}));