简体   繁体   English

有没有办法检测元素是否被 jQuery 的 click() 单击?

[英]Is there a way to detect if an element was clicked by jQuery's click()?

I'm not too sure if this is possible, but is there anyway of achieving this?我不太确定这是否可能,但无论如何有办法实现这一目标吗? I want to have some basic protection from scripts that will automatically register click events on my buttons, eg: pesky bots.我想对脚本有一些基本的保护,这些脚本会自动在我的按钮上注册点击事件,例如:讨厌的机器人。

I want to only allow clicks with the mouse, not clicks triggered by javascript itself.我只想允许用鼠标点击,而不是由 javascript 本身触发的点击。

Any ideas or other methods of protection against this?任何想法或其他保护方法?

You want to identify that the click event has triggered through element click or through any js code, right?您想确定单击事件是通过元素单击还是通过任何 js 代码触发的,对吗?

In that case you can use "event" object returned by "click" event在这种情况下,您可以使用“click”事件返回的“event”对象

You can use您可以使用

event.hasOwnProperty('originalEvent')

above statement returns true if the event is triggered by clicking on target element else returns false如果事件是通过单击目标元素触发的,则上述语句返回 true,否则返回 false

Note: Note sure how foolproof is this.注意:请注意这是多么万无一失。

There is an originalEvent property that will be set when the user triggers the click event, so you can check it I think当用户触发点击事件时,将设置一个 originalEvent 属性,因此您可以检查它我认为

$('div').click(function(e){
    console.log(e, this, e.originalEvent)
    if(e.originalEvent){
        console.log('user clicked')
    }
}).click();

Demo: Fiddle演示:小提琴

You can register a mouseDown event handler on the button and only process the .click() event if the .click() event occurs within a certain time after the mouseDown (eg a second).您可以在按钮上注册 mouseDown 事件处理程序,如果.click()事件发生在 mouseDown 之后的特定时间内(例如一秒),则仅处理.click()事件。

function now() {
    return (new Date()).getTime();
}

$("#myButton").on("mousedown click", function(e) {
    var self = $(this);
    if (e.type === "mousedown") {
        self.data("mousedownTime", now()); 
    } else {
        var mouseTime = self.data("mousedownTime");
        if (mouseTime && now() - mouseTime < 1000) {
            // process the click here
        }
    }
});

This could be turned into a jQuery plugin method that would do this for you, fairly easily.这可以变成一个 jQuery 插件方法,可以很容易地为您完成此操作。

jQuery.fn.realClick = function(fn) {
    this.on("mousedown click", function(e) {
        var self = $(this);
        if (e.type === "mousedown") {
            self.data("mousedownTime", now()); 
        } else {
            var mouseTime = self.data("mousedownTime");
            if (mouseTime && now() - mouseTime < 1000) {
                // process the real click here
                return fn(e);
            }
        }
    });
}

$("#myButton").realClick(function(e) {
    // your click processing code here
    // only gets called if a click event was
    // preceded by a mousedown event within 1 second
});

One possible way to achieve this is using Google Analytics.实现这一目标的一种可能方法是使用 Google Analytics。 Something like the below maybe, tweaked to your goals?也许像下面这样的东西,调整到你的目标?

<p class="downloadsmall">download: <a href="jpg/LOW/1.jpg" onClick="_gaq.push(['_trackPageview', '/downloads/img/LowRes/1.jpg']);">Low Res</a></p>


<!-- GA track all onClicks -->

<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'YOUR COOL GA ID']);
  _gaq.push(['_trackPageview']);
  _gaq.push(['_trackEvent', 'Downloads', 'JPG', '/downloads/img/"+x+"']);

$(function(){
    $('.downloadsmall a').on("click", function(){
        var theHREF = $(this).attr('href'),
            myGAQ   = _gaq || [];
        myGAQ.push(['_trackPageview', theHREF]);
        myGAQ.push(['_trackEvent', 'Downloads', 'JPG', theHREF]);

    });
});

</script>

<!-- End GA track all onClicks -->

This?这个?

$('#id').on('click', function(){
  console.log('clicked');
});

I'm not sure if I 100% understand your question.我不确定我是否 100% 理解你的问题。 That would obviously log something if it was clicked.如果点击它,这显然会记录一些东西。 Are you looking for a way to prevent that from happening?您是否正在寻找防止这种情况发生的方法?

You can use Event.isTrusted .您可以使用Event.isTrusted

The isTrusted read-only property of the Event interface is a Boolean that is true when the event was generated by a user action, and false when the event was created or modified by a script or dispatched via EventTarget.dispatchEvent(). Event 接口的 isTrusted 只读属性是一个布尔值,当事件由用户操作生成时为 true,当事件由脚本创建或修改或通过 EventTarget.dispatchEvent() 调度时为 false。

Example:例子:

 document.getElementById("click-me").addEventListener("click", function(e) { if (e.isTrusted) { console.log("This click is real"); } else { console.log("This click is not real"); } }); document.getElementById("test").addEventListener("click", function(e) { document.getElementById("click-me").click() });
 <button id="click-me">Click me</button> <button id="test">Click to simulate click on the other button</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 JQuery使用单击元素的href侦听单击和警报 - JQuery listen to click and alert with clicked element's href 如何检测单击的元素是否不是jQuery中元素的子级? - How to detect if clicked element was not a child of an element in jQuery? 单击时单击jQuery,以在未单击时触发动态元素 - jQuery on click for dynamic element triggering when not clicked 什么是最简单的访问方式<li>单击的元素是通过 jQuery 内部的吗? - What's the easiest way to access the <li> an element that's clicked is within via jQuery? jQuery:如果与单击元素的类匹配,则删除用户单击时的元素类 - jQuery: Remove class of elements on user click if it's a match with the class of the clicked element jquery没有检测到click元素 - jquery does not detect click on child element 追加元素后,Jquery 未检测到单击 - Jquery not detect click after append of element 检测点击可调整大小元素的调整大小手柄 - Detect click on resizable element's resize handle 在元素外部单击另一个链接时,最有效的返回到先前状态的方法是什么? (jQuery的) - What's the most efficient way to return to previous state when another link is clicked outside the element? (jQuery) JavaScript / jQuery-是否可以检测点击类型? - JavaScript / jQuery - Any way to detect click type?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM