-1

我在页面上有链接。我希望能够附加链接要去的 URL;例如,现有链接如下所示:

<a href="/url/urlpage.ext">Click here</a>
<a href="http://www.google.com">Google</a>

我希望能够使用 jQuery 浏览页面上的所有链接并附加到 URL 的开头,如果它们没有 http,请添加它......所以最终 URL 看起来像这样:

<a href="http://www.example.com/url/urlpage.ext">Click here</a>
<a href="http://www.google.com">Google</a>
4

3 回答 3

3

你可以做 :

$("a:not([href^=http])").each(function(){
    $(this).attr('href', 'http://www.mysite.com'+$(this).attr('href'))
});
于 2013-07-08T17:45:50.303 回答
1

你可以做:

$("a").each(function() {
    //Get the current href
    var href = $(this).attr("href");

    //Check for http in the beginning
    if (href.indexOf("http://") == -1) {

        //Add to it and set it
        href = "http://" + href;
        $(this).attr("href", href);
    }
});
于 2013-07-08T17:45:37.640 回答
0
//for every <a>
$('a').each(function() {
    // get existing href
    var href= $(this).attr('href'),
    // start at the beginning, get first 7 chars
    var first7char = href.substr(0, 7);
    // if not http or https
    if(first7char !== 'http://' || 'https://'){
        // insert  http://
    $(this).attr('href', 'http://' + href');
    }
});
于 2013-07-08T17:59:18.493 回答