I've been Googling for a while and can't seem to find an answer to this question. My problem is as follows:
For my jquery, I need my links to be relative rather than absolute. My PHP is set to return relative urls and everything is working fine, until I test it in IE7. For some开发者_开发知识库 reason, IE7 keeps changing my relative urls to abosulute, which breaks my js script. Is this normal? Is there a way to get around it?
For example:
IE8, Chrome, Firefox, Safari etc -
<a href='/page' onclick='click_handler(this);return false;'>clicky</a>
IE7 -
<a href='http://www.myurl.com/page' onclick='click_handler(this);return false;'>clicky</a>
What I do is grab the baseUrl at init, like:
var baseUrl = window.location.href.substring(0, window.location.href.lastIndexOf("/") + 1);
... and then in my URL handler, strip the baseUrl:
var url = $(this).attr("href").replace(baseUrl, "");
Also you can check if the href is "normalized" using .support()
:
$.support.hrefNormalized
(returns true
if the browser makes no modifications when grabbing an href value, so it's currently false in IE.)
If I were you, I'd use browser detection and add a clause to strip the URL down to the relative path. I'm not 100% familiar with jQuery, but I imagine you could do it with a simple split and reconstruction, or REGEX query.
See jQuery URL Parser Plugin: http://plugins.jquery.com/project/url_parser
Looks like it has something to do with security issues - http://blogs.msdn.com/ie/archive/2005/08/15/452006.aspx
Right, it seems the best way to do this is to strip the domain out in jQuery. For anyone that has a similar problem, here is what my click event handler looks like:
var href_attr = element.getAttribute('href');
if (href_attr.indexOf('http://')>-1) {
href_attr = href_attr.substr(location.href.length-1);
};
Here's a modified version of JKS's answer that uses split instead of substring. A little more elegant IMO:
stripBaseUrl : function(url){
var urlArray = url.split("/");
return urlArray[urlArray.length - 1];
}
精彩评论