How to Update Tag's Href Attribute Using JavaScript
When attempting to modify an tag's href property via JavaScript upon button click, you may face difficulties. Let's explore solutions to address this issue.
First, it's crucial to provide the tag with a href value, as leaving it empty will trigger a page refresh on click. Consider the following options:
Assign a non-empty href value:
<code class="html"><a href="#" id="abc">jhg</a></code>
Prevent page scrolling:
<code class="html"><a href="#" id="abc" onclick="f1(); return false;">jhhghj</a></code>
Include the return false statement within the f1 function:
<code class="html"><a href="#" onclick="return f1();">jhhghj</a></code>
Alternatively, you can adopt the unobtrusive approach:
<code class="html"><a href="#" id="abc">jhg</a> <a href="#" id="myLink">jhhghj</a> <script type="text/javascript"> document.getElementById("myLink").onclick = function() { document.getElementById("abc").href="xyz.php"; return false; }; </script></code>
This approach separates JavaScript from the HTML, improving code organization and adaptability.
The above is the detailed content of How to Dynamically Update an Tag\'s href Attribute Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!