我有一个附加到事件的处理程序,我希望它只在由人类触发时执行,而不是由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)
我认为这样做的唯一方法trigger
是根据文档在调用中传入一个额外的参数.
$('.checkbox').change(function(e, isTriggered){
if (!isTriggered)
{
alert ('human');
}
});
$('.checkbox').trigger('change', [true]); //doesn't alert
Run Code Online (Sandbox Code Playgroud)
接受的答案对我不起作用.已经有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)
目前大多数浏览器都支持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() 。
归档时间: |
|
查看次数: |
52859 次 |
最近记录: |