我只是想知道如何使用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>

但它并没有起作用:(

什么好主意吗?


当前回答

在javascript中,通过它的id或类名抓取元素,然后应用.click()使点击发生 如:

document.getElementById("btnHandler").click();

其他回答

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

我们必须使用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>

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

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

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

$("#mytest1").click();
document.getElementById("element").click()

只需从DOM中选择元素。该节点具有单击函数,您可以调用该函数。

Or

document.querySelector("#element").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