GoodPrintf

 

JavaScript获取href的值

1.当href的值为正常网址时:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8">
    <head th:include="include :: header"></head>
    <title></title>
</head>
<body>
    <a style="font-size: 24px;" href="https://www.cnblogs.com/">博客园</a><br><br>
</body>
<script type="text/javascript" >
var as = document.getElementsByTagName('a');
for(var i=0,j=as.length;i<j;i++)
{
    console.log(as[i].getAttribute("href"))
    console.log(as[i].href)
}
</script>
</html>

得到的结果如下

 2.当href的值为普通字符串时

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <title></title>
 5     <meta charset="utf-8">
 6     <head th:include="include :: header"></head>
 7     <title></title>
 8 </head>
 9 <body>
10     <a style="font-size: 24px;" href="www.cnblogs.com/">精密成型保养提醒表</a><br><br>
11 </body>
12 <script type="text/javascript" >
13 var as = document.getElementsByTagName('a');
14 for(var i=0,j=as.length;i<j;i++)
15 {
16     console.log(as[i].getAttribute("href"))
17     console.log(as[i].href)
18 }
19 </script>
20 </html>

结果如下

 

一般情况下,直接使用as[i].getAttribute("href")更为可靠

posted on 2023-04-19 17:05  GoodPrintf  阅读(433)  评论(0编辑  收藏  举报

导航