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

但它并没有起作用:(

什么好主意吗?


当前回答

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

其他回答

[编辑2022]这个答案真的过时了。现代化。原始答案在底部。

使用元素。dispatchEvent使用新创建的所需类型的Event。

下面是一个使用事件委托的例子。

Fork这个stackblitz项目来玩它。

// Note: {bubbles: true} because of the event delegation ... document.addEventListener(`click`, handle); document.addEventListener(`virtualhover`, handle); // the actual 'trigger' function const trigger = (el, etype, custom) => { const evt = custom ?? new Event( etype, { bubbles: true } ); el.dispatchEvent( evt ); }; // a custom event ;) const vHover = new CustomEvent(`virtualhover`, { bubbles: true, detail: `red` }); setTimeout( _ => trigger( document.querySelector(`#testMe`), `click` ), 1000 ); function handle(evt) { if (evt.target.id === `clickTrigger`) { trigger(document.querySelector(`#testMe`), `click`); } if (evt.type === `virtualhover`) { evt.target.style.color = evt.detail; return setTimeout( _ => evt.target.style.color = ``, 1000 ); } if (evt.target.id === `testMe`) { document.querySelector(`#testMeResult`) .insertAdjacentHTML(`beforeend`, `<p>One of us clicked #testMe. It was <i>${evt.isTrusted ? `<b>you</b>` : `me`}</i>.</p>`); trigger( document.querySelector(`#testMeResult p:last-child`), `virtualhover`, vHover ); } } body { font: 1.2rem/1.5rem verdana, arial; margin: 2rem; } #testMe { cursor: pointer; } p { margin: 0.2rem 0; } <div id="testMe"> Test me can be clicked </div> <p><button id='clickTrigger'>Click #testMe</button></p> <div id="testMeResult"></div>

老答案是:

这是我做的。这很简单,但很有效: 函数eventFire(el, etype){ if (el.fireEvent) { 埃尔。fireEvent('on' + etype); }其他{ var evObj = document.createEvent('Events'); evObj。initEvent(etype, true, false); el.dispatchEvent (evObj); } }

老实说,这里的答案都不适合我的具体情况。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();

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

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

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

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