JavaScript 判断页面是否存在按钮并模拟点击
使用 JavaScript 判断页面是否存在按钮并模拟点击的操作步骤如下:
- 获取按钮元素: 使用
document.querySelector()获取页面中指定的按钮元素,例如:
const button = document.querySelector('.list-bnt');
- 获取链接元素: 获取页面中指定的链接元素,例如:
const currentLi = document.querySelector('.d-on');
const nextLi = currentLi.nextElementSibling;
const nextLink = nextLi.querySelector('a');
- 判断按钮和链接是否存在: 使用
if语句判断获取到的按钮和链接元素是否为空,例如:
if (button && nextLink) {
// 模拟点击按钮
button.click();
// 模拟点击链接
nextLink.click();
} else {
// 弹窗提示
alert('页面缺少按钮或链接');
}
完整代码示例:
const button = document.querySelector('.list-bnt');
const currentLi = document.querySelector('.d-on');
const nextLi = currentLi.nextElementSibling;
const nextLink = nextLi.querySelector('a');
if (button && nextLink) {
// 模拟点击按钮
button.click();
// 模拟点击链接
nextLink.click();
} else {
// 弹窗提示
alert('页面缺少按钮或链接');
}
通过以上步骤,您可以判断页面是否存在特定按钮,并根据判断结果执行相应的操作。
原文地址: https://www.cveoy.top/t/topic/bLB0 著作权归作者所有。请勿转载和采集!