javascript - 如何使用 Javascript 触发 div 元素的事件监听器?
问题描述
我想使用javascript模拟在此页面https://aqicn.org/data-platform/register/上单击“下载CSV数据...”按钮。问题是按钮是<div>
带有事件侦听器的 a 而不是<button>
or <input>
。
我想我必须使用document.dispatchEvent()
,但我不知道要放什么参数。我将不胜感激任何帮助。
解决方案
您可以使用 触发事件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');
推荐阅读
- google-maps - Google map API 按单词查找地点
- amazon-kinesis - 适用于 Web 应用程序的 Kinesis 生产者
- python - 如何在 Python 中从管道中读取?
- focus - Svelte:将焦点设置到自定义 Web 组件中的开槽元素
- c# - 从 C# 控制台应用程序访问 Azure Active Directory 并获得“权限不足,无法完成操作”。错误信息
- r - 链接重定向问题 - 使用 Rvest 在 R 中进行 Web Scraping
- microservices - 在 Hazelcast 缓存中存储常用的微服务实体?
- assembly - 编写汇编时使用哪个寄存器是否重要?
- oop - 面向对象设计——以可扩展的方式设计家具系统
- javascript - 元素在滚动时反复上下滑动