I try to create a jQuery snippet which detect the window's url and depends on the window's href , change the a tag 's href.
My code is so far:
(function($) {
"use strict";
$(document).ready(function() {
$(window).on('load', function() {
var changeLink = document.getElementById("LinkTag");
console.log('it is running');
if ($(window).location.href() == "pageUrl") {
changeLink.href = "website1";
} else {
changeLink.href = "website2";
}
});
});
})(jQuery);
Thanks
A number of things going on here:
location.href
is not a jQuery method; it's a property of the regular window object. Use window.location.href
instead of $(window).location.href()
. window.location.href
, which includes things (such as the protocol, subdomains, hash, and URL parameters) that can vary while still pointing to the same page; window.location.pathname
is usually a safer bet (assuming you're trying to match a specific page.) document.ready
and a window.onload
. I've removed the redundant layers here. document.getElementById
for its jQuery equivalent here. $(document).ready(function() { var pageUrl = "/js"; // This is the path when running in a stackoverflow snippet var changeLink = $("#LinkTag"); if (window.location.pathname == pageUrl) { changeLink.attr("href","//example.com"); } else { changeLink.attr("href","//somethingelse.com"); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a id="LinkTag">Link</a>
Repalce your $(window).location
for just window.location
if (window.location.href == "pageUrl")
changeLink.href = "website1";
else
changeLink.href = "website2";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.