开发者

How do I check href attribute and if needed add full url address?

开发者 https://www.devze.com 2023-03-16 20:44 出处:网络
I want to check the href attribute and if it does not contain the full path, I want to replace it with full URL? Should I use JavaScript which does that but don\'t work on IE 8?

I want to check the href attribute and if it does not contain the full path, I want to replace it with full URL? Should I use JavaScript which does that but don't work on IE 8?

My JS:

开发者_开发百科
fullUrl = $(this).filter('[href^='+document.location.protocol+']').attr('href') 
    ? true : false;

url = fullUrl ? 
    $(this).filter('[href^='+document.location.protocol+']').attr('href') 
    : document.location.protocol + '//' + document.domain + $(this).attr('href');

I need to check if href contain full url or not:

href: "/path/other.html" (part)

href:"http://domain.com/path/other.html" (full url)

And then if i have part url href, i must add domain and recreate href to full url!


The full url is available via the .href property.

Typically there's no need to set it to the attribute, but if you want to, you could do this:

$('a[href]').attr('href', function() { return this.href; });

This finds all <a> elements that have an href attribute, and updates its href using the attr()[docs] method by passing a function as the second parameter, which returns the value of the .href property.


If you just wanted a list of them, you can use the map()[docs] method.

var hrefs = $('a[href]').map(function() { return this.href; }).get();

Example: http://jsfiddle.net/EDhhD/


EDIT:

If you want to explicitly check that the path isn't already the full path, just add an if statement to my first example.

$('a[href]').attr('href', function(i,hrf) { 
    if( hrf.indexOf( 'http' ) !== 0 ) return this.href; 
});


I guess you want this:

$(this).attr('href', function(i, v) {
    if ( v.indexOf('http:') === -1 ) {
        v = document.location.protocol + '//' + document.domain + '/' + v; 
    }
    return v;
});

Live demo: http://jsfiddle.net/simevidas/bwmQ5/


I don't think you can get a meaningful result of calling attr on multiple items. You should do your check/replacement in a loop, one item at a time:

$(this).filter('[href^='+document.location.protocol+']').each(function(){
    var fullUrl = $(this).attr('href') ? true : false;
    var url = fullUrl ? $(this).attr('href') : document.location.protocol + '//' + document.domain + $(this).attr('href');
    alert(url);
});


This solution will ensure all anchors on your page have the protocol in the href:

$(document).ready(function()
{  
    var str_len = document.location.protocol.length;
    $('a').each(function()
    {
        if($(this).attr('href').substring(0,str_len) != document.location.protocol)
        {
            $(this).attr('href',document.location.protocol + '//' + $(this).attr('href'));
        }
    });
});

http://jsfiddle.net/3XQXL/

0

精彩评论

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