Simulate click on GMail div button with JS

為{幸葍}努か 提交于 2019-12-22 05:20:34

问题


I want to simulate click on GMail COMPOSE button using JS without JQuery.

Here is button:

<div class="T-I J-J5-Ji T-I-KE L3" role="button" tabindex="0" gh="cm" 
style="-webkit-user-select: none;">COMPOSE</div>

Here is my js:

var element = document.getElementsByClassName('T-I-KE')[0];
element.click();

Result:undefined in all browsers

Image: http://i.imgur.com/4IX9DZX.png

Already tried that:

var event = document.createEvent("MouseEvent");
event.initEvent("click",true,true);
var element=document.getElementsByClassName("T-I-KE")[0];
element.dispatchEvent(event);

Result:true. But nothing happens.

Image: http://i.imgur.com/pwVqukP.png


回答1:


After two days i am finally got an answer!

That button listens mouseDown and mouseUP events. Working code:

var down = new MouseEvent('mousedown');
var up = new MouseEvent('mouseup');
var elem = document.getElementsByClassName("T-I-KE")[0];
elem.dispatchEvent(down);
elem.dispatchEvent(up);



回答2:


The function getElementsByClassName(classString) will return the elements with the class of exactly the string that you pass to it. Try using querySelector, like this

document.querySelector(".T-I-KE");

That will return the first element with the class T-I-KE. If you want ALL the elementes with that class, call the function querySelectorAll instead



来源:https://stackoverflow.com/questions/28477428/simulate-click-on-gmail-div-button-with-js

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