问题
When I use method click()
to click the button, the submission failed.
But, when I use the mouse to click the button on that webpage, (the submit form is same) it works.
HTML file:
<button xmlns="http://www.w3.org/1999/xhtml" class="ui-button button1" type="submit" id="create">
<span>
<span>Create</span>
</span>
</button>
My userscript file:
document.getElementById("create").click();
How do I click the button using HTML DOM click()?
回答1:
The click method does not always work. Try sending a click
event similarly to this answer:
var targBtn = document.querySelector ("#create");
var clickEvent = document.createEvent ('MouseEvents');
clickEvent.initEvent ('click', true, true);
targBtn.dispatchEvent (clickEvent);
But also beware that the button may not operate on clicks at all. See "Choosing and activating the right controls on an AJAX-driven site".
The button may operate on mousedown
, mouseup
, or some combination of events. Use the techniques from that question to activate the control. Link to the target page if you can't get it to work.
回答2:
maybe instead of clicking the button. You can submit the form in javascript as
document.getElementByName('form1').submit();
as it fulfills your requirement.
回答3:
Wrap the call in an anonymous self executing construct like so:
(function(){
document.getElementById("create").click();
})();
This will simulate a click
when the javascript is loaded.
回答4:
if at all you are flexible about value of your button then do this:
<button xmlns="http://www.w3.org/1999/xhtml" class="ui-button button1" value="submit" type="submit" id="create">
document.getButtonByValue('submit').click();
This works just fine.
jsfiddle link
来源:https://stackoverflow.com/questions/15997550/dom-click-is-not-working-on-this-button