我需要一个 Javascript 如果没有找到按钮,可以通过类id点击按钮的代码,否则重载页面。
请帮我解决这个问题。
在MDN文档上就有这样的例子。
你可以检查按钮是否存在:如果不存在,则重新加载页面;否则,发射一个 MouseEvent
在...上 window
.
const main = () => {
document.addEventListener('DOMContentLoaded', onReady);
};
const onReady = () => {
if (document.querySelector('.button-you-want') == null) {
//location.reload(); // This will cause the frame to reload infinitely...
return;
}
const btn = document.querySelector('.button-you-want');
btn.addEventListener('click', handleClick);
const event = new MouseEvent('click', {
view: window,
bubbles: true,
cancelable: true
});
btn.dispatchEvent(event);
};
const handleClick = (e) => {
console.log('Success!');
};
main();
<button class="not-the-button-you-are-looking-for">Hey</button>
<!-- Enable to not reload...
<button class="button-you-want">Hey</button>
-->