
usuario171523
Tengo un hipervínculo en mi página. Estoy tratando de automatizar una cantidad de clics en el hipervínculo con fines de prueba. ¿Hay alguna forma de simular 50 clics en el hipervínculo usando JavaScript?
<a href="#" target="_blank" onclick="javascript:Test("Test");">MSDN</a>
Estoy buscando el activador de eventos onClick del JavaScript.

instancia de mi
Haciendo un solo clic en un elemento HTML: simplemente hazlo element.click()
. La mayoría de los principales navegadores admiten esto.
Para repetir el clic más de una vez: Agregue una ID al elemento para seleccionarlo de forma única:
<a href="#" target="_blank" id="my-link" onclick="javascript:Test('Test');">Google Chrome</a>
y llama al .click()
método en su código JavaScript a través de un bucle for:
var link = document.getElementById('my-link');
for(var i = 0; i < 50; i++)
link.click();

Juan Mendes
ACTUALIZAR
Esta era una respuesta antigua. Hoy en día solo deberías usar hacer clic. Para disparos de eventos más avanzados, 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'));
Respuesta Original
Esto es lo que uso: http://jsfiddle.net/mendesjuan/rHMCy/4/
Actualizado para trabajar con IE9+
/**
* 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);
}
};
Tenga en cuenta que llamar fireEvent(inputField, 'change');
no significa que realmente cambiará el campo de entrada. El caso de uso típico para activar un evento de cambio es cuando establece un campo mediante programación y desea que se llame a los controladores de eventos desde que llama input.value="Something"
no activará un evento de cambio.

黄雨伞
Qué
l.onclick();
hace exactamente llamar al onclick
funcion de l
es decir, si ha configurado uno con l.onclick = myFunction;
. Si no ha configurado l.onclick
, no hace nada. A diferencia de,
l.click();
simula un clic y activa todos los controladores de eventos, ya sea que se agreguen con l.addEventHandler('click', myFunction);
en HTML o de cualquier otra forma.
Estoy bastante avergonzado de que haya tantas aplicabilidades parciales incorrectas o no reveladas.
La forma más fácil de hacer esto es a través de Chrome u Opera (mis ejemplos usarán Chrome) usando la Consola. Ingrese el siguiente código en la consola (generalmente en 1 línea):
var l = document.getElementById('testLink');
for(var i=0; i<5; i++){
l.click();
}
Esto generará el resultado requerido.

Manolo
.click()
no funciona con Android (mira documentos de mozilla, en la sección móvil). Puede desencadenar el evento de clic con este método:
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();
}
}
Desde esta publicación
Usar un marco de prueba
Esto podría ser útil – http://seleniumhq.org/ – Selenium es un sistema de prueba automatizado de aplicaciones web.
Puedes crear pruebas usando el plugin de Firefox IDE de selenio
Activación manual de eventos
Para activar eventos manualmente de la manera correcta, deberá usar diferentes métodos para diferentes navegadores, ya sea el.dispatchEvent
o el.fireEvent
donde el
será su elemento ancla. Creo que ambos requerirán la construcción de un objeto de evento para pasar.
La forma alternativa, no del todo correcta, rápida y sucia sería esta:
var el = document.getElementById('anchorelementid');
el.onclick(); // Not entirely correct because your event handler will be called
// without an Event object parameter.

Fatih Hayrioğlu
IE9+
function triggerEvent(el, type){
var e = document.createEvent('HTMLEvents');
e.initEvent(type, false, true);
el.dispatchEvent(e);
}
Ejemplo de uso:
var el = document.querySelector('input[type="text"]');
triggerEvent(el, 'mousedown');
Fuente: https://plainjs.com/javascript/events/trigger-an-event-11/