利用浏览器console控制台实现JS网页点击

利用浏览器console控制台实现JS网页点击

RecordInLife 2020-10-13 16:35:16 3086 收藏 9
文章标签: JavaScript
版权
适用场景:需要网页中的某个页面中选择N多个特定的元素,然后对他们依次点击(比如选中)。

1、根据页面中DOM元素分析页面的结构找出共同点,方便定位元素
除了JS中常用的document.getElementById(“id值”)、document.getElementsByTagName(“标签名”)…之外,他们都比较限定,有没其他的方式根据自定义属性去获取元素?
比如:

<input type="checkbox" name="hobby1">爱好1--游泳<br/>
<input type="checkbox" name="hobby2">爱好2--唱歌<br/>
<input type="checkbox" name="hobby1">爱好1--阅读<br/>
<input type="checkbox" name="hobby1">爱好1--游戏<br/>
<input type="checkbox" name="hobby2">爱好2--编程<br/>
<input type="checkbox" name="hobby1">爱好1--write<br/>
<input type="checkbox" name="hobby3">爱好3--tik tok<br/>
<input type="checkbox" name="hobby2">爱好2--刷抖音<br/>
<input type="checkbox" name="hobby1">爱好1--呦呵<br/>

想要定位到 input标签中name属性为hobby2的标签,如何实现?

# 原生js
//document.querySelector("input[name='hobby2']") ---这种只能查找到第一个元素
document.querySelectorAll("input[name='hobby2']") //这能查所有
# jquery
$("input[name='hobby2']")

2、为找到的元素实现点击事件

# 原生js
var objs = document.querySelectorAll("input[name='hobby2']");

//不使用定时器实现点击
objs[1].click();

//使用定时器实现一次点击
var o = setTimeout(objs[2].click(),5000);
//使用定时器实现连续输出
setInterval(function(){console.log(1)},1000)

# jquery
$(objs[1]).click();

效果图:

 

 例如:

document.getElementById('fm-login-id').value = "user用户名";
document.getElementById('fm-login-password').value = "mm123456";

如果复杂的
//     $(document.getElementsByTagName("iframe")[2]).contents().find("#s_filter_frame")[0].contentWindow.document.getElementById("o_id").value = "设置的input值"

————————————————
版权声明:本文为CSDN博主「RecordInLife」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/itzhengmaolin/article/details/109052454

posted @ 2021-10-21 17:04  前端白雪  阅读(3604)  评论(0编辑  收藏  举报