我只是想知道如何使用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文件中调用。 在这段代码中,要么单击按钮显示警报,要么在某些条件下或无条件地调用它

函数ss () { alert (' dddddddddddddddddddddddd '); } var mybtn = . getelementbyid (btn); mybtn.click (); <!DOCTYPE html > < html > < >头 <标题>页面标题< /名称> < / >头 身体< > <h1>这是一个标题</h1> <p>这是一个段落 <button id="btn" onclick="ss()">点击查看</按钮> . < /身体> < / html >

其他回答

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

这个例子将触发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

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

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

如果事件没有被触发,请使用timeout

setTimeout(function(){ document.getElementById('your_id').click(); }, 200); 

老实说,这里的答案都不适合我的具体情况。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来避免所有的浏览器检测吗?使用jQuery,它将像下面这样简单:

$("#mytest1").click();