我只是想知道如何使用JavaScript来模拟对元素的单击。

目前我有:

function simulateClick(control) {
  if (document.all) {
    control.click();
  } else {
    var evObj = document.createEvent('MouseEvents');
    evObj.initMouseEvent('click', true, true, window, 1, 12, 345, 7, 220, false, false, true, false, 0, null );
    control.dispatchEvent(evObj);
  }
}
<a href="http://www.google.com" id="mytest1">test 1</a><br>

<script type="text/javascript">
    simulateClick(document.getElementById('mytest1'));
</script>

但它并没有起作用:(

什么好主意吗?


当前回答

这没有很好的记录,但我们可以非常简单地触发任何类型的事件。

这个例子将触发50双击按钮:

let theclick = new Event(“dblclick”) for (let i = 0;i < 50;i++){ action.dispatchEvent(theclick) } <button id=“action” ondblclick=“out.innerHTML+='Wtf '”>TEST</button> <div id=“out”></div>

The Event interface represents an event which takes place in the DOM. An event can be triggered by the user action e.g. clicking the mouse button or tapping keyboard, or generated by APIs to represent the progress of an asynchronous task. It can also be triggered programmatically, such as by calling the HTMLElement.click() method of an element, or by defining the event, then sending it to a specified target using EventTarget.dispatchEvent(). https://developer.mozilla.org/en-US/docs/Web/API/Event

https://developer.mozilla.org/en-US/docs/Web/API/Event/Event

其他回答

模拟事件类似于创建自定义事件。模拟鼠标事件

我们必须使用document.createEvent()创建MouseEvent。 然后使用initMouseEvent(),我们必须设置将要发生的鼠标事件。 然后在您想要模拟事件的元素上分派鼠标事件。

在下面的代码中,我使用了setTimeout,以便按钮在1秒后自动单击。

const div = document.querySelector('div'); div.addEventListener('click', function(e) { console.log('Simulated click'); }); const simulatedDivClick = document.createEvent('MouseEvents'); simulatedDivClick.initEvent( 'click', /* Event type */ true, /* bubbles */ true, /* cancelable */ document.defaultView, /* view */ 0, /* detail */ 0, /* screenx */ 0, /* screeny */ 0, /* clientx */ 0, /* clienty */ false, /* ctrlKey */ false, /* altKey */ false, /* shiftKey */ 0, /* metaKey */ null, /* button */ null /* relatedTarget */ ); // Automatically click after 1 second setTimeout(function() { div.dispatchEvent(simulatedDivClick); }, 1000); <div> Automatically click </div>

比如一些简单的东西怎么样:

document.getElementById('elementID').click();

IE也支持。

你考虑过使用jQuery来避免所有的浏览器检测吗?使用jQuery,它将像下面这样简单:

$("#mytest1").click();
var elem = document.getElementById('mytest1');

// Simulate clicking on the specified element.
triggerEvent( elem, 'click' );

/**
 * Trigger the specified event on the specified element.
 * @param  {Object} elem  the target element.
 * @param  {String} event the type of the event (e.g. 'click').
 */
function triggerEvent( elem, event ) {
  var clickEvent = new Event( event ); // Create the event.
  elem.dispatchEvent( clickEvent );    // Dispatch the event.
}

参考

https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events https://codepen.io/felquis/pen/damDA

使用jQuery可以节省大量空间。你只需要使用:

$('#myElement').trigger("click")