在之前的文章《如何用 jQuery 為段落元素設(shè)置動(dòng)畫(huà)》中給大家介紹了怎么用 jQuery 為段落元素設(shè)置動(dòng)畫(huà),感興趣的朋友可以去閱讀了解一下~
本文將給大家介紹怎么通過(guò)JavaScript在單擊按鈕后更改<a>標(biāo)簽的href值。
在我們?nèi)粘i_(kāi)發(fā)過(guò)程中難免會(huì)遇到這類(lèi)要求,所以就不要錯(cuò)過(guò)本文啦~
下面介紹兩種實(shí)現(xiàn)方法:
第一種方法
代碼如下:
<!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body style="text-align:center;"> <h1 style="color:#ff311f"> PHP中文網(wǎng) </h1> <h3> 更改href屬性值 </h3> <a href="https://www.baidu.com/"> Go to 百度! </a> <br><br> <button onclick="myFunction()"> 點(diǎn)擊更改跳轉(zhuǎn)鏈接 </button> <script type="text/javascript"> function myFunction() { var link = document.querySelector("a"); link.getAttribute("href"); link.setAttribute("href", "https://www.php.cn/"); link.textContent = "歡迎來(lái)到PHP中文網(wǎng)!"; } </script> </body> </html>
效果如下:
第二種方法
代碼如下:
<!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body style="text-align:center;"> <h1 style="color:#ff7a03"> PHP中文網(wǎng) </h1> <h3> 更改href屬性值 </h3> <a href="https://www.baidu.com" id="myLink"> Go to 百度 </a> <br><br> <button onclick="myFunction()"> 點(diǎn)擊更改跳轉(zhuǎn)鏈接 </button> <script type="text/javascript"> function myFunction() { document.getElementById('myLink').href ="https://www.php.cn"; document.getElementById("myLink") .textContent = "歡迎來(lái)到PHP中文網(wǎng)!"; } </script> </body> </html>
效果如下:
相關(guān)介紹:
通過(guò)五種方式選擇元素:
-
document.querySelector() 方法:它返回與查詢(xún)匹配的第一個(gè)元素。
-
document.querySelectorAll() 方法:它返回與查詢(xún)匹配的所有元素。
-
document.getElementById() 方法:它返回與 id 匹配的一個(gè)元素。
-
document.getElementsByClassName() 方法:返回與類(lèi)匹配的所有元素。
-
document.getElementsByTagName() 方法:它返回與標(biāo)簽名稱(chēng)匹配的元素列表。
DOM 允許屬性操作。屬性控制 HTML 標(biāo)記的行為或提供有關(guān)標(biāo)記的附加信息。JavaScript 提供了多種操作 HTML 元素屬性的方法。
以下方法用于操作屬性:
-
getAttribute() 方法:它返回元素上某個(gè)屬性的當(dāng)前值,如果元素上不存在指定的屬性,則返回 null。
-
setAttribute() 方法:它更新指定元素上現(xiàn)有屬性的值,否則添加具有指定名稱(chēng)和值的新屬性。
-
removeAttribute() 方法:用于移除指定元素的屬性。
最后給大家推薦《JavaScript基礎(chǔ)教程》~歡迎大家學(xué)習(xí)~