[英]changing a tag href depends on window.location.href
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. 我尝试创建一个jQuery代码段,该代码段检测窗口的url并取决于窗口的href ,更改标记的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; location.href
不是jQuery方法; it's a property of the regular window object. window.location.href
instead of $(window).location.href()
. window.location.href
代替$(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.href
匹配,该文件包含的内容(例如协议,子域,哈希和URL参数)在指向同一页面时可能会有所不同; window.location.pathname
is usually a safer bet (assuming you're trying to match a specific page.) window.location.pathname
通常是一个比较安全的选择(假设您要匹配特定的页面。) document.ready
and a window.onload
. document.ready
和window.onload
。 I've removed the redundant layers here. document.getElementById
for its jQuery equivalent here. document.getElementById
换成了它的jQuery等效项。 $(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
仅将
window.location
换成$(window).location
.location
if (window.location.href == "pageUrl")
changeLink.href = "website1";
else
changeLink.href = "website2";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.