问题
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