Click source in JavaScript and jQuery, human or automated?

老子叫甜甜 提交于 2019-11-27 08:10:48

问题


We all know that you can simulate click or any other event on an element using one of these ways:

$('#targetElement').trigger('eventName');
$('#targetElement').click();

I have encountered a situation in which, I should know how an element is clicked. I should know if it's been clicked automatically via code, or by pressing mouse button. Is there anyway I can do it without hacks or workarounds? I mean, is there anything built into browsers' event object, JavaScript, or jQuery that can tell us whether click has been initiated by a human action or by code?


回答1:


Try this:

$('#targetElement').click(function(event, generated) {
    if (generated) {
        // Event was generated by code, not a user click.
    } else {
        // Event was generated by a user click.
    }
});

Then, to make this work, you have to trigger them like this:

$('#targetElement').trigger('click', [true]);

See this jsfiddle.




回答2:


Check out event.which, it'll be undefined if triggered with code.

$(document).click(function(event) {
    if (event.which) {
       // Triggered by the event.
    } else {
       // Triggered with code.
    }
});

jsFiddle.




回答3:


Here's one way I have found (tested in Chrome)

$('#foo').click(function(e) {
    if (e.originalEvent)
        alert('Has e (manual click)');
    else
        alert('No e (triggered)');
});

See here for testing: http://jsfiddle.net/ZPD8w/2/




回答4:


In your immediate event handler, provide an e parameter. If the click is automated (via code), this e would be undefined (no need to check e.target as @alex has said):

$('#targetElement').click(function(e){
   if(e)
   {
      // Click is triggered by a human action
   }
   else
   {
     // Click is triggered via code
   }
});


来源:https://stackoverflow.com/questions/6982072/click-source-in-javascript-and-jquery-human-or-automated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!