首页 > 解决方案 > 如何使用 Javascript 触发 div 元素的事件监听器?

问题描述

我想使用javascript模拟在此页面https://aqicn.org/data-platform/register/上单击“下载CSV数据...”按钮。问题是按钮是<div>带有事件侦听器的 a 而不是<button>or <input>

在此处输入图像描述

我想我必须使用document.dispatchEvent(),但我不知道要放什么参数。我将不胜感激任何帮助。

在此处输入图像描述

标签: javascripthtml

解决方案


您可以使用 触发事件document.createEvent

// http://youmightnotneedjquery.com/#trigger_native
const triggerNative = (el, eventName) => {
  const event = document.createEvent('HTMLEvents');
  event.initEvent(eventName, true, false);
  el.dispatchEvent(event);
};

const btn = document.querySelector('#historical-aqidata .primary.button');
const handleClick = e => console.log('clicked button...');

btn.addEventListener('click', handleClick); // Pre-existing event listener
triggerNative(btn, 'click');                // Call the event
html,
body {
  width: 100%;
  height: 100%;
  padding: 0;
  margin: 0;
}

#historical-aqidata {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.button {
  display: flex;
  padding: 1em;
  border-radius: 0.5em;
  font-weight: bold;
  cursor: pointer;
}

.primary {
  background: #0085D6;
  color: #FFFFFF;
}

.primary:hover {
  background: #419ED3;
  color: #FFFFFF;
}

.as-console-wrapper { max-height: 5em !important; }
<div id="historical-aqidata">
  <div class="ui large primary button">Download the SCV data for Seoul</div>
</div>


注意: MDN 建议您改用事件构造函数

“许多与 一起使用的方法createEvent,例如initCustomEvent,已被弃用。请改用事件构造函数。”

// http://youmightnotneedjquery.com/#trigger_custom
const triggerCustom = (el, eventName, data) => {
  let event;
  if (window.CustomEvent && typeof window.CustomEvent === 'function') {
    event = new CustomEvent(eventName, { detail: data });
  } else {
    event = document.createEvent('CustomEvent');
    event.initCustomEvent(eventName, true, true, data);
  }
  el.dispatchEvent(event);
};

您可以像调用原生函数一样调用自定义函数,因为数据是可选的。

triggerCustom(btn, 'click');

推荐阅读