检查事件是否由人类触发

Dzi*_*mid 134 jquery

我有一个附加到事件的处理程序,我希望它只在由人类触发时执行,而不是由trigger()方法触发.我该如何区分?

例如,

$('.checkbox').change(function(e){
  if (e.isHuman())
  {
    alert ('human');
  }
});

$('.checkbox').trigger('change'); //doesn't alert
Run Code Online (Sandbox Code Playgroud)

Nic*_*tti 203

您可以检查e.originalEvent:如果已定义,则单击为人:

看看小提琴http://jsfiddle.net/Uf8Wv/

$('.checkbox').change(function(e){
  if (e.originalEvent !== undefined)
  {
    alert ('human');
  }
});
Run Code Online (Sandbox Code Playgroud)

我在小提琴中的例子:

<input type='checkbox' id='try' >try
<button id='click'>Click</button>

$("#try").click(function(event) {
    if (event.originalEvent === undefined) {
        alert('not human')
    } else {
        alert(' human');
    }


});

$('#click').click(function(event) {
    $("#try").click();
});
Run Code Online (Sandbox Code Playgroud)


Ken*_*cer 18

比上面更直接的是:

$('.checkbox').change(function(e){
  if (e.isTrigger)
  {
    alert ('not a human');
  }
});

$('.checkbox').trigger('change'); //doesn't alert
Run Code Online (Sandbox Code Playgroud)

  • 虽然这很诱人并且在实践中可能很舒适,但请注意,jQuery开发人员不希望将`isTrigger`转移到公共API [截至此时](https://github.com/jquery/api.jquery.com/问题/ 319). (2认同)

det*_*lor 7

我认为这样做的唯一方法trigger是根据文档在调用中传入一个额外的参数.

$('.checkbox').change(function(e, isTriggered){
  if (!isTriggered)
  {
    alert ('human');
  }
});

$('.checkbox').trigger('change', [true]); //doesn't alert
Run Code Online (Sandbox Code Playgroud)

示例:http://jsfiddle.net/wG2KY/


Erg*_*gec 7

接受的答案对我不起作用.已经有6年了,jQuery从那以后发生了很大的变化.

例如,event.originalEvent返回始终true使用jQuery 1.9.x. 我的意思是对象总是存在但内容却不同.

那些使用较新版本的jQuery的人可以试试这个.适用于Chrome,Edge,IE,Opera,FF

if ((event.originalEvent.isTrusted === true && event.originalEvent.isPrimary === undefined) || event.originalEvent.isPrimary === true) {
    //Hey hooman it is you
}
Run Code Online (Sandbox Code Playgroud)


fel*_*ins 7

目前大多数浏览器都支持event.isTrusted

if (e.isTrusted) {
  /* The event is trusted: event was generated by a user action */
} else {
  /* The event is not trusted */
}
Run Code Online (Sandbox Code Playgroud)

文档

所述isTrusted只读的属性Event接口是一个Boolean时由用户操作生成的事件,并且虚假 事件创建或修改在由脚本或者经由调度 EventTarget.dispatchEvent()

  • 请注意,“isTrusted”实际上并不意味着“由人类生成”,尽管有些文档是这样总结的。这些“或”子句很重要。请参阅:/sf/ask/2565980091/ (2认同)