简体   繁体   中英

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.

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:

  1. 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() .
  2. It looks like you're trying to match the string "pageUrl" instead of a variable -- unless that was intended as a sample string in the question, the variable name shouldn't be enclosed in quotes.
  3. You probably don't want to match against the full 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.)
  4. It's not necessary to wrap your script in an IIFE and a document.ready and a window.onload . I've removed the redundant layers here.
  5. (Optional) Mixing jQuery methods and vanilla methods can be confusing to maintain, because you have to keep track of which variables contain jQuery objects and which contain references to regular DOM nodes. Since you've already got jQuery elsewhere, I swapped out your 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM