admin管理员组文章数量:1128156
I have a hyperlink in my page. I am trying to automate a number of clicks on the hyperlink for testing purposes. Is there any way you can simulate 50 clicks on the hyperlink using JavaScript?
<a href="#" target="_blank" onclick="javascript:Test("Test");">MSDN</a>
I'm looking for onClick event trigger from the JavaScript.
I have a hyperlink in my page. I am trying to automate a number of clicks on the hyperlink for testing purposes. Is there any way you can simulate 50 clicks on the hyperlink using JavaScript?
<a href="#" target="_blank" onclick="javascript:Test("Test");">MSDN</a>
I'm looking for onClick event trigger from the JavaScript.
Share Improve this question edited Feb 20, 2020 at 19:42 Brian Tompsett - 汤莱恩 5,87572 gold badges61 silver badges133 bronze badges asked Mar 4, 2010 at 18:02 user171523user171523 4,3354 gold badges38 silver badges50 bronze badges9 Answers
Reset to default 400Performing a single click on an HTML element: Simply do element.click()
. Most major browsers support this.
To repeat the click more than once: Add an ID to the element to uniquely select it:
<a href="#" target="_blank" id="my-link" onclick="javascript:Test('Test');">Google Chrome</a>
and call the .click()
method in your JavaScript code via a for loop:
var link = document.getElementById('my-link');
for(var i = 0; i < 50; i++)
link.click();
You should just use click. For more advanced event firing, use dispatchEvent.
const body = document.body;
body.addEventListener('click', e => {
console.log('clicked body');
});
console.log('Using click()');
body.click();
console.log('Using dispatchEvent');
body.dispatchEvent(new Event('click'));
Original Answer - Obsolete
Here is what I use for IE9+ http://jsfiddle.net/mendesjuan/rHMCy/4/
/**
* Fire an event handler to the specified node. Event handlers can detect that the event was fired programatically
* by testing for a 'synthetic=true' property on the event object
* @param {HTMLNode} node The node to fire the event handler on.
* @param {String} eventName The name of the event without the "on" (e.g., "focus")
*/
function fireEvent(node, eventName) {
// Make sure we use the ownerDocument from the provided node to avoid cross-window problems
var doc;
if (node.ownerDocument) {
doc = node.ownerDocument;
} else if (node.nodeType == 9){
// the node may be the document itself, nodeType 9 = DOCUMENT_NODE
doc = node;
} else {
throw new Error("Invalid node passed to fireEvent: " + node.id);
}
if (node.dispatchEvent) {
// Gecko-style approach (now the standard) takes more work
var eventClass = "";
// Different events have different event classes.
// If this switch statement can't map an eventName to an eventClass,
// the event firing is going to fail.
switch (eventName) {
case "click": // Dispatching of 'click' appears to not work correctly in Safari. Use 'mousedown' or 'mouseup' instead.
case "mousedown":
case "mouseup":
eventClass = "MouseEvents";
break;
case "focus":
case "change":
case "blur":
case "select":
eventClass = "HTMLEvents";
break;
default:
throw "fireEvent: Couldn't find an event class for event '" + eventName + "'.";
break;
}
var event = doc.createEvent(eventClass);
event.initEvent(eventName, true, true); // All events created as bubbling and cancelable.
event.synthetic = true; // allow detection of synthetic events
// The second parameter says go ahead with the default action
node.dispatchEvent(event, true);
} else if (node.fireEvent) {
// IE-old school style, you can drop this if you don't need to support IE8 and lower
var event = doc.createEventObject();
event.synthetic = true; // allow detection of synthetic events
node.fireEvent("on" + eventName, event);
}
};
Note that calling fireEvent(inputField, 'change');
does not mean it will actually change the input field. The typical use case for firing a change event is when you set a field programmatically and you want event handlers to be called since calling input.value="Something"
won't trigger a change event.
What
l.onclick();
does is exactly calling the onclick
function of l
, that is, if you have set one with l.onclick = myFunction;
. If you haven't set l.onclick
, it does nothing. In contrast,
l.click();
simulates a click and fires all event handlers, whether added with l.addEventHandler('click', myFunction);
, in HTML, or in any other way.
I'm quite ashamed that there are so many incorrect or undisclosed partial applicability.
The easiest way to do this is through Chrome or Opera (my examples will use Chrome) using the Console. Enter the following code into the console (generally in 1 line):
var l = document.getElementById('testLink');
for(var i=0; i<5; i++){
l.click();
}
This will generate the required result
.click()
does not work with Android (look at mozilla docs, at mobile section). You can trigger the click event with this method:
function fireClick(node){
if (document.createEvent) {
var evt = document.createEvent('MouseEvents');
evt.initEvent('click', true, false);
node.dispatchEvent(evt);
} else if (document.createEventObject) {
node.fireEvent('onclick') ;
} else if (typeof node.onclick == 'function') {
node.onclick();
}
}
From this post
IE9+
function triggerEvent(el, type){
var e = document.createEvent('HTMLEvents');
e.initEvent(type, false, true);
el.dispatchEvent(e);
}
Usage example:
var el = document.querySelector('input[type="text"]');
triggerEvent(el, 'mousedown');
Source: https://plainjs.com/javascript/events/trigger-an-event-11/
Use a testing framework
This might be helpful - http://seleniumhq.org/ - Selenium is a web application automated testing system.
You can create tests using the Firefox plugin Selenium IDE
Manual firing of events
To manually fire events the correct way you will need to use different methods for different browsers - either el.dispatchEvent
or el.fireEvent
where el
will be your Anchor element. I believe both of these will require constructing an Event object to pass in.
The alternative, not entirely correct, quick-and-dirty way would be this:
var el = document.getElementById('anchorelementid');
el.onclick(); // Not entirely correct because your event handler will be called
// without an Event object parameter.
Please call trigger function any where and button will click.
<a href="#" id="myBtn" title="" >Button click </a>
function trigger(){
document.getElementById("myBtn").click();
}
Fair warning:
element.onclick()
does not behave as expected. It only runs the code within onclick="" attribute
, but does not trigger default behavior.
I had similar issue with radio button not setting to checked, even though onclick
custom function was running fine. Had to add radio.checked = "true";
to set it. Probably the same goes and for other elements (after a.onclick()
there should be also window.location.href = "url";
)
本文标签: How can I trigger a JavaScript event clickStack Overflow
版权声明:本文标题:How can I trigger a JavaScript event click - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736718681a1949343.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论