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

但它并没有起作用:(

什么好主意吗?


当前回答

老实说,这里的答案都不适合我的具体情况。Jquery是出了问题,所以所有这些答案都未经测试。我会说我从上面的@mnishiguchi的回答中建立了这个答案,但这是唯一一件实际上最终有效的事情。

// select the element by finding the id of mytest1
const el = document.querySelector('#mytest1');

// pass the element to the simulateClick function
simulateClick( el );

function simulateClick(element){
    trigger( element, 'mousedown' );
    trigger( element, 'click' );
    trigger( element, 'mouseup' );

    function trigger( elem, event ) {
      elem.dispatchEvent( new MouseEvent( event ) );
    }
}

其他回答

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

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

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

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

老实说,这里的答案都不适合我的具体情况。Jquery是出了问题,所以所有这些答案都未经测试。我会说我从上面的@mnishiguchi的回答中建立了这个答案,但这是唯一一件实际上最终有效的事情。

// select the element by finding the id of mytest1
const el = document.querySelector('#mytest1');

// pass the element to the simulateClick function
simulateClick( el );

function simulateClick(element){
    trigger( element, 'mousedown' );
    trigger( element, 'click' );
    trigger( element, 'mouseup' );

    function trigger( elem, event ) {
      elem.dispatchEvent( new MouseEvent( event ) );
    }
}
document.getElementById('elementId').dispatchEvent(new MouseEvent("click",{bubbles: true, cancellable: true}));

按照这个链接了解鼠标事件使用Javascript和浏览器兼容性相同

https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent#Browser_compatibility

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

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