In the previous article "How to use jQuery to animate paragraph elements", I introduced how to use jQuery to animate paragraph elements. Interested friends can read and learn more~
This article will introduce to you how to change the href value of the tag after clicking the button through JavaScript.
We will inevitably encounter such requirements in our daily development process, so don’t miss this article~
The following are two implementation methods:
The first method
The code is as follows:
<!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>
The effect is as follows:
The second method
The code is as follows:
<!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>
The effect is as follows:
JavaScript Basics Tutorial" ~ Welcome everyone to learn ~
The above is the detailed content of Change href value of tag after clicking button via JavaScript. For more information, please follow other related articles on the PHP Chinese website!