在jQuery中,如何区分程序化点击和用户点击? [英] In jQuery, how can I tell between a programmatic and user click?

查看:90
本文介绍了在jQuery中,如何区分程序化点击和用户点击?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我定义了一个点击处理程序:

$("#foo").click(function(e){

});

我如何在函数处理程序中判断事件是通过编程方式触发还是由用户触发?

解决方案

您可以查看事件对象e.如果事件是由真正的点击触发的,则在e内将包含诸如clientXclientYpageXpageY等的内容,它们将是数字.这些数字与触发单击时的鼠标位置有关,但是即使单击是通过键盘启动的,也可能会出现这些数字.如果事件是由$x.click()触发的,则e中将没有常规位置值.您还可以查看 originalEvent属性,如果事件来自$x.click().

也许是这样的:

$("#foo").click(function(e){
    if(e.hasOwnProperty('originalEvent'))
        // Probably a real click.
    else
        // Probably a fake click.
});

这是一个可供使用的小沙箱: http://jsfiddle.net/UtzND/

Say I have a click handler defined:

$("#foo").click(function(e){

});

How can I, within the function handler, tell whether the event was fired programmatically, or by the user?

解决方案

You could have a look at the event object e. If the event was triggered by a real click, you'll have things like clientX, clientY, pageX, pageY, etc. inside e and they will be numbers; these numbers are related to the mouse position when the click is triggered but they will probably be present even if the click was initiated through the keyboard. If the event was triggered by $x.click() then you won't have the usual position values in e. You could also look at the originalEvent property, that shouldn't be there if the event came from $x.click().

Maybe something like this:

$("#foo").click(function(e){
    if(e.hasOwnProperty('originalEvent'))
        // Probably a real click.
    else
        // Probably a fake click.
});

And here's a little sandbox to play with: http://jsfiddle.net/UtzND/

这篇关于在jQuery中,如何区分程序化点击和用户点击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆