Note that there are some explanatory texts on larger screens.

plurals
  1. POjQuery replacing relative links
    primarykey
    data
    text
    <p>Hopefully someone can explain some odd behavior I've encountered with jQuery. The following script is looking for relative links on my page and replacing them with absolute links. </p> <pre><code>$(document).ready(function() { $("a[href^='/']").each(function(){ var cur_href = $(this).prop("href"); $(this).prop("href", 'http://www.mysite.com'+cur_href); }); }); </code></pre> <p>I'm using this script on a page that will be served up over https but I don't want all of my navigation to link to https pages. Since my navigation are global includes, this seemed like the easiest way to fix the problem.</p> <p>The issue I'm encountering comes in the actual replacement. The second line of the script correctly matches all relative links on the page and then runs the replacement part of the script. It is in the replacement, line 4, where I get some weird results. After this part of the script runs, my URLs end up looking like this:</p> <blockquote> <p><strong>http://www.mysite.comhttps//www.mysite.com/mypage.htm</strong></p> </blockquote> <p>Obviously isn't doing what I want. It seems like the first part of the script is matching the relative URL but when the replacement part fires the browser has already tacked on the domain information.</p> <p>The only thing I've found so far that actually does what I want is to write the replacement anticipating what the browser has tacked on:</p> <pre><code>this.href = this.href.replace(/^https:\/\/www\.mysite\.com\//, "http://www.mysite.com/"); </code></pre> <p>Is there a better way to do this?</p> <hr> <p>Edit: <a href="http://jsfiddle.net/zneMp/" rel="nofollow">here is a jsfiddle of the problem</a>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload