简体   繁体   English

div按钮上的JQuery click()不会触发

[英]JQuery click() on a div button won't fire

I am trying to emulate a user's click on a site who's code I do not control. 我试图模仿用户点击我无法控制的代码的网站。 The element I am trying to engage with a div acting as button. 我尝试与div作为按钮的元素。

<div role="button" class="c-T-S a-b a-b-B a-b-Ma oU v2" aria-disabled="false" style="-webkit-user-select: none;" tabindex="0">
    Generate
</div>

The event listeners that are associated with element (according to Chrome's inspector) are: 与元素关联的事件监听器(根据Chrome的检查员)是:

在此输入图像描述

And I am simply trying to click the button using: 而我只是试图点击按钮使用:

var button = $('.c-T-S.a-b.a-b-B.a-b-Ma.oU.v2')
button.click()

... but nothing happens. ......但没有任何反应。 The selector is valid, as verified by: 选择器有效,经过验证:

alert($('.c-T-S.a-b.a-b-B.a-b-Ma.oU.v2').length); // alerts "1"

I have tried permutations of all the event handlers 我尝试过所有事件处理程序的排列

button.trigger('click');
button.mouseover().mousedown().mouseup()
button.trigger('mouseover', function() { button.trigger('mousedown', function() { button.trigger('mouseup'); });  });

... but still nothing. ......但仍然没有。 How can I simulate a click on this div? 如何模拟此div的点击?

In case it is not clear, I am trying to simulate a click on this div and trigger the original function, not define a new click function on the element. 如果不清楚,我试图模拟这个div上的单击并触发原始函数,而不是在元素上定义新的单击函数。

UPDATE UPDATE

Many of these answer do indeed click the button, but don't produce the same result as manually clicking the button. 其中许多答案确实单击了按钮,但不会产生与手动单击按钮相同的结果。 So it appears the problem is not necessarily clicking the button per se, but emulating a real click. 所以问题似乎不一定是点击按钮本身,而是模仿真正的点击。

I have made a FIDDLE to simulate your "non-clickable" button. 我做了一个FIDDLE来模拟你的“不可点击”按钮。 The blue div there has the same eventListeners attached as you have shown in your question. 其中的蓝色div具有与您在问题中显示的相同的eventListeners。 Playing around ended up with following results: 四处游戏结果如下:

1) Let's get the DOM-element first: 1)让我们先获取DOM元素:

var button = document.getElementsByClassName('.c-T-S.a-b.a-b-B.a-b-Ma.oU.v2')[0];

2) The page doesn't include jQuery. 2)该页面不包含jQuery。 So all eventListeners there are attached by native .addEventListener() . 因此,所有eventListener都由native .addEventListener() .addEventListener native .addEventListener()附加。 If you use jQuery to trigger events, it triggers only the events that are attached by jQuery, but not the native attached events. 如果使用jQuery触发事件,它只触发jQuery附加的事件,而不触发本机附加事件。 That means: 这意味着:

$(button).trigger('mousedown'); // this doesn't work
button.dispatchEvent(new Event('mousedown')); // this should work

3) As Scimonster pointed out, there is no click-eventListener attached. 3)正如Scimonster指出的那样,没有附加click-eventListener。 That means: 这意味着:

$(button).trigger('click'); // doesn't work anyway, see 2)
// next works, but has no visible result on the page,
// because there is no click-handler to do anything:
button.dispatchEvent(new Event('click'));

4) The click-event fires when the mousebutton goes up. 4)当鼠标按钮上升时,点击事件触发。 When the mouseup -event is used instead it looks like a click. 当使用mouseup -event时,它看起来像是一个单击。 In the fiddle the mouseup makes the red div visible. 在小提琴中,mouseup使红色div可见。 You may try to trigger the mouseup-event by adding this line to the code: 您可以尝试通过将以下行添加到代码来触发mouseup事件:

button.dispatchEvent(new Event('mouseup')); // "works", but has no visible result

The mouseup-handler is "hidden" by the mouseover - and mouseout -events, the first attaches it and the latter removes it. mouseup-handler由mouseovermouseout -events“隐藏”,第一个附加它,后者删除它。 That way mouseup has only a result when mouse is over the button. 这样,当鼠标悬停在按钮上时,mouseup只有一个结果。 I assume your google-page does something similar to cover the click-event. 我假设你的谷歌页面做了类似的事情来涵盖点击事件。

5) What you should try: 5)你应该尝试什么:

First trigger some single events in native way: 首先以本机方式触发一些单个事件:

button.dispatchEvent(new Event('eventName'));

If that gives no usable results use some reasonable combinations of events: 如果没有给出可用的结果,请使用一些合理的事件组合:

button.dispatchEvent(new Event('mouseover'));
button.dispatchEvent(new Event('mousedown'));
// or:
button.dispatchEvent(new Event('mousedown'));
button.dispatchEvent(new Event('mouseup')); // or: .....

There are many ways to combine events so that a single event doesn't do anything, but only the right combination works. 有许多方法可以组合事件,以便单个事件不会执行任何操作,但只有正确的组合才有效。

EDIT According to your invitation to investigate the source I found two ways: 编辑根据您调查来源的邀请,我找到了两种方法:

1) The button itself has no eventListeners attached. 1)按钮本身没有附加eventListeners。 The button is wrapped in an <a> -tag. 该按钮包含在<a> -tag中。 This tag is parent of the button and its attribute jsaction 's value tells that <a> has listeners for click , focus , and mousedown . 此标记是按钮的父级,其属性jsaction的值告诉<a>具有clickfocusmousedown侦听器。 Targeting it directly works: 直接针对它起作用:

button.parentElement.dispatchEvent(new Event('click'));

2) If you want to click the button itself you must trigger an event that bubbles up the DOM to reach an element that has a click-handler. 2)如果要单击按钮本身,则必须触发一个事件,该事件会使DOM冒泡以到达具有单击处理程序的元素。 But when creating an event with new Event('name') , its bubbles -property defaults to false . 但是当使用new Event('name')创建事件时,其bubbles -property默认为false It was my bad not thinking of that. 我没有想到这一点。 . So the following works directly on the button: 所以以下工作直接在按钮上工作:

button.dispatchEvent(new Event('click', {bubbles: true}));

EDIT 2 Digging deeper in whats going on on that page yielded an usable result: 编辑2深入挖掘该页面上的最新内容,产生了可用的结果:

It has been found that the page takes care of the mouse-pointer position and right order of the events, probable to distinguish wether a human or a robot/script triggers the events. 已经发现页面处理鼠标指针位置和事件的正确顺序,可能区分人或机器人/脚本触发事件。 Therefore this solution uses the MouseEvent - object containing the clientX and clientY properties, which holds the coordinates of the pointer when the event is fired. 因此,此解决方案使用MouseEvent - 包含clientXclientY属性的对象,该属性在触发事件时保存指针的坐标。

A natural "click" on an element always triggers four events in given order: mouseover , mousedown , mouseup , and click . 一个自然的“点击”的元素总是触发给定的顺序四个事件: mouseovermousedownmouseup ,并click To simulate a natural behaviour mousedown and mouseup are delayed. 为了模拟自然行为, mousedownmouseup被延迟了。 To make it handy all steps are wrapped in a function which simulates 1) enter element at it's topLeft corner, 2) click a bit later at elements center. 为方便起见,所有步骤都包含在一个函数中,该函数模拟1)在其左上角输入元素,2)稍后点击元素中心。 For details see comments. 详情见评论。

function simulateClick(elem) {
    var rect = elem.getBoundingClientRect(), // holds all position- and size-properties of element
        topEnter = rect.top,
        leftEnter = rect.left, // coordinates of elements topLeft corner
        topMid = topEnter + rect.height / 2,
        leftMid = topEnter + rect.width / 2, // coordinates of elements center
        ddelay = (rect.height + rect.width) * 2, // delay depends on elements size
        ducInit = {bubbles: true, clientX: leftMid, clientY: topMid}, // create init object
        // set up the four events, the first with enter-coordinates,
        mover = new MouseEvent('mouseover', {bubbles: true, clientX: leftEnter, clientY: topEnter}),
        // the other with center-coordinates
        mdown = new MouseEvent('mousedown', ducInit),
        mup = new MouseEvent('mouseup', ducInit),
        mclick = new MouseEvent('click', ducInit);
    // trigger mouseover = enter element at toLeft corner
    elem.dispatchEvent(mover);
    // trigger mousedown  with delay to simulate move-time to center
    window.setTimeout(function() {elem.dispatchEvent(mdown)}, ddelay);
    // trigger mouseup and click with a bit longer delay
    // to simulate time between pressing/releasing the button
    window.setTimeout(function() {
        elem.dispatchEvent(mup); elem.dispatchEvent(mclick);
    }, ddelay * 1.2);
}

// now it does the trick:
simulateClick(document.querySelector(".c-T-S.a-b.a-b-B.a-b-Ma.oU.v2"));

The function does not simulate the real mouse movement being unnecessary for the given task. 该功能不会模拟给定任务不必要的真实鼠标移动

$('.cTS.ab.abB.ab-Ma.oU.v2').trigger('click'); does the job - the click event is triggered. 完成工作 - 触发点击事件。

.trigger() : Execute all handlers and behaviors attached to the matched elements for the given event type. .trigger():执行附加到给定事件类型的匹配元素的所有处理程序和行为。

http://api.jquery.com/trigger/ http://api.jquery.com/trigger/

 $('.cTS.ab.abB.ab-Ma.oU.v2').on('click', function() { alert( $( this ).text() ); }); $('.cTS.ab.abB.ab-Ma.oU.v2').trigger('click'); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div role="button" class="cTS ab abB ab-Ma oU v2" aria-disabled="false" style="-webkit-user-select: none;" tabindex="0"> Generate </div> 

From the image you posted of event handlers, click is not one of them . 从您发布的事件处理程序的图像中, 单击不是其中之一 Programmatically triggering a click is not the same as doing so naturally. 以编程方式触发点击与自然地这样做是不一样的。 Mouse enter/leave/press events are not fired here. 此处不会触发鼠标进入/离开/按下事件。

I actually tried on the link you gave and it works. 我实际上试过你给的链接,它的工作原理。 There's no jquery on the page, so have to go by native methods. 页面上没有jquery,因此必须使用本机方法。

var click= document.createEvent("MouseEvents");
click.initMouseEvent("click", true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);

document.getElementsByClassName('c-T-S a-b a-b-B')[0].dispatchEvent(click)

I have created a JS Fiddle for this and it is working fine. 我为此创建了一个JS小提琴 ,它工作正常。 I have used following 我用过以下

$('.c-T-S.a-b.a-b-B.a-b-Ma.oU.v2').click(function(){
    alert("clicked");
});
$('.c-T-S.a-b.a-b-B.a-b-Ma.oU.v2').click();// This will trigger click event programatically

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM