在之前的文章《如何用jQuery 為段落元素設定動畫》中給大家介紹了怎麼用jQuery 為段落元素設定動畫,有興趣的朋友可以去閱讀了解一下~
本文將介紹給大家怎麼透過JavaScript在點擊按鈕後更改標籤的href值。
在我們日常開發過程中難免會遇到這類要求,所以就不要錯過本文啦~
下面介紹兩種實作方法:
第一種方法
程式碼如下:
<!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body style="text-align:center;"> <h1 style="color:#ff311f"> PHP中文网 </h1> <h3> 更改href属性值 </h3> <a href="https://www.baidu.com/"> Go to 百度! </a> <br><br> <button onclick="myFunction()"> 点击更改跳转链接 </button> <script type="text/javascript"> function myFunction() { var link = document.querySelector("a"); link.getAttribute("href"); link.setAttribute("href", "https://www.php.cn/"); link.textContent = "欢迎来到PHP中文网!"; } </script> </body> </html>
效果如下:
##第二種方法程式碼如下:<!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body style="text-align:center;"> <h1 style="color:#ff7a03"> PHP中文网 </h1> <h3> 更改href属性值 </h3> <a href="https://www.baidu.com" id="myLink"> Go to 百度 </a> <br><br> <button onclick="myFunction()"> 点击更改跳转链接 </button> <script type="text/javascript"> function myFunction() { document.getElementById('myLink').href ="https://www.php.cn"; document.getElementById("myLink") .textContent = "欢迎来到PHP中文网!"; } </script> </body> </html>
以上是透過JavaScript在點擊按鈕後變更標籤的href值的詳細內容。更多資訊請關注PHP中文網其他相關文章!