开发者

Prepend Subfolder to All Links with jQuery

I am currently working on a site in a staging environment located at www.example.com/staging. All of the links for the site have been set relatively (ex: /about/). I am trying to write some simple jQuery to add "/staging" to every link on the pages, so I don't have to change all the links for the week or so it is in the staging environmen开发者_Go百科t. I know the HTML tag is an option, but because the links are being added dynamically with ExpressionEngine that doesn't seem to work. I think the jQuery should be fairly simple. Here is what I have, but something isn't quite right:

$(function() {
  var href = $('a').attr('href');
  $(href).prepend('/staging');
});

Thanks in advance for the help.


Try this:

$(function() {
  $('a').each(function() {
    var href = $(this).attr('href');
    $(this).attr('href', '/staging' + href);
  });
});


$(function() {
  $('a').each(function() {
    $(this).attr('href', '/staging' + $(this).attr('href'));
  });
});

$(href) doesn't find anything because it's just the value of the attribute.


The URL examples you have posted (/about/ and /staging) are not relative; they are rooted. These paths will not do what you seem to be trying to do here.

Relative URLs never start with the slash; they start with a path part (a name, or dots). Having the slash at the beginning forces the browser to look from the root of the host for the link, just like having the slash at the beginning of a path name in a file system does.


An alternative to jQuery is to use the <base> tag.

Adding <base href="http://www.example.com/staging/" /> inside your <head> tag will make all of your /about/ (etc) links work the way that you want.

Actually, I don't think this will work for you. It would work if you had URLs like about/ which are real relative links. /about/ isn't a relative link. I'll leave this answer here in case someone find this later through a google search and needs a solution for relative links.

If your URLs were of the less common form ./about/ then this solution would work. Browsers would treat (and display) the URL ./about/ as http://www.example.com/about/ without a <base> tag or as http://www.example.com/staging/about/ if you set a <base> tag in the way above.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜