Home  >  Article  >  Web Front-end  >  How to Prevent Page Reloads When Changing Anchor Tag href Attribute with JavaScript?

How to Prevent Page Reloads When Changing Anchor Tag href Attribute with JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-27 08:22:02325browse

How to Prevent Page Reloads When Changing Anchor Tag href Attribute with JavaScript?

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="https://www.php.cn/link/93ac0c50dd620dc7b88e5fe05c70e15b" onclick="f1()">...jhhghj</a></code>

Alternatively, you can prevent the page from scrolling using:

<code class="html"><a href="https://www.php.cn/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>

...jhhghj

For a more unobtrusive approach, employ an external JavaScript file:

...jhg
...jhhghj

<script></p> <pre class="brush:php;toolbar:false">document.getElementById(&quot;myLink&quot;).onclick = function() { document.getElementById(&quot;abc&quot;).href = &quot;xyz.php&quot;; return false; };</pre> <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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn