将外部链接设置为橙色
重要性:3
通过修改链接的style
属性,将所有外部链接设置为橙色。
外部链接是指
- 其
href
包含://
- 但不是以
http://internal.com
开头的链接。
示例
<
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
=
"
https://node.org.cn"
>
https://node.org.cn</
a
>
</
li
>
<
li
>
<
a
href
=
"
http://internal.com/test"
>
http://internal.com/test</
a
>
</
li
>
</
ul
>
<
script
>
// setting style for a single link
let
link =
document.
querySelector
(
'a'
)
;
link.
style.
color =
'orange'
;
</
script
>
结果应该是
首先,我们需要找到所有外部引用。
有两种方法。
第一种是使用 document.querySelectorAll('a')
找到所有链接,然后过滤掉我们需要的部分。
let
links =
document.
querySelectorAll
(
'a'
)
;
for
(
let
link of
links)
{
let
href =
link.
getAttribute
(
'href'
)
;
if
(
!
href)
continue
;
// no attribute
if
(
!
href.
includes
(
'://'
)
)
continue
;
// no protocol
if
(
href.
startsWith
(
'http://internal.com'
)
)
continue
;
// internal
link.
style.
color =
'orange'
;
}
请注意:我们使用 link.getAttribute('href')
。而不是 link.href
,因为我们需要来自 HTML 的值。
…另一种更简单的方法是在 CSS 选择器中添加检查。
// look for all links that have :// in href
// but href doesn't start with http://internal.com
let
selector =
'a[href*="://"]:not([href^="http://internal.com"])'
;
let
links =
document.
querySelectorAll
(
selector)
;
links.
forEach
(
link
=>
link.
style.
color =
'orange'
)
;