Home > Web Front-end > JS Tutorial > body text

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

Patricia Arquette
Release: 2024-10-27 08:22:02
Original
324 people have browsed it

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>
Copy after login

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>
Copy after login

or return false from the f1() function:

<code class="javascript">function f1() {
    document.getElementById("abc").href = "xyz.php";          
    return false;
}</code>
Copy after login

...jhhghj

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

...jhg
...jhhghj

<script></p> <div class="code" style="position:relative; padding:0px; margin:0px;"><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><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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!