使用场景
对数组进行循环判断,有多种条件需要判断,然后对符合所有条件的那一项数据进行操作
案例如下
使用
querySelectorAll可以获取页面所有a 标签数组,然后对符合条件的a 标签进行处理

代码实现
<!DOCTYPE HTML>
<html>
<body>
<a name="list">The list:</a>
<ul>
<li><a href="http://google.com">http://google.com</a></li>
<li><a href="/tutorial">/tutorial.html</a></li>
<li><a href="local/path">local/path</a></li>
<li><a href="ftp://ftp.com/my.zip">ftp://ftp.com/my.zip</a></li>
<li><a href="http://nodejs.org">http://nodejs.org</a></li>
<li><a href="http://internal.com/test">http://internal.com/test</a></li>
</ul>
</body>
</html>
- 第一种思路:直接if判断,把多种条件使用
&&放一起,对符合所有条件的项进行处理
<script>
// 第一种思路
let links = document.querySelectorAll('a');
for(let link of links){
let atr = link.getAttribute('href');
if(atr && !atr.startsWith('http://internal.com') && atr.includes('://')){
link.style.color = 'orange'
}
}
</script>
- 第二种思路:使用continue,不符合条件的跳过本次循环
<script>
let links = document.querySelectorAll('a');
for (let link of links) {
let href = link.getAttribute('href');
if (!href) continue; // 没有特性
if (!href.includes('://')) continue; // 没有协议
if (href.startsWith('http://internal.com')) continue; // 内部的
link.style.color = 'orange';
}
</script>
案例文章参考:https://zh.javascript.info/dom-attributes-and-properties
文章展示了如何使用JavaScript的querySelectorAll选取页面上的a标签,并通过循环和条件判断对符合特定条件(如非内部链接且包含协议)的链接元素进行样式操作,提供了两种不同的逻辑实现方式。
631

被折叠的 条评论
为什么被折叠?



