Changing the href Attribute of an Anchor Tag Using JavaScript on Button Click
In web development, the need to dynamically modify the href attribute of an anchor tag on button click frequently arises. Here's how you can achieve this using JavaScript.
In the provided code snippet, the f1() function alters the href attribute of an element with the ID "abc" to "xyz.php." However, the provided code will not work as expected.
By default, clicking on an anchor tag triggers a page reload. To prevent this, you need to add an empty href attribute to the anchor tag, such as:
<code class="html"><a href="//m.sbmmt.com/link/93ac0c50dd620dc7b88e5fe05c70e15b" onclick="f1()">...jhhghj</a></code>
Alternatively, you can prevent the page from scrolling using:
<code class="html"><a href="//m.sbmmt.com/link/93ac0c50dd620dc7b88e5fe05c70e15b" onclick="f1(); return false;">...jhhghj</a></code>
or return false from the f1() function:
<code class="javascript">function f1() { document.getElementById("abc").href = "xyz.php"; return false; }</code>
For a more unobtrusive approach, employ an external JavaScript file:
<script></p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">document.getElementById("myLink").onclick = function() { document.getElementById("abc").href = "xyz.php"; return false; };</pre><div class="contentsignin">Copy after login</div></div> <p></script>
The above is the detailed content of How to Prevent Page Reloads When Changing Anchor Tag href Attribute with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!