JQuery change all links on page

 $(function(){
            $('a').each(function(){
                        var x=this.href;
                        this.href="www.somesitename.com/filter"+this.href;
                  });
         });

I wrote a jQuery script above to add some site name to all links on the page, but it does not work properly.

+3
source share
6 answers

I wonder why you are using jQuery for such basic behavior ...

therefore the BASE tag exists for

Specify the default URL and default target for all links on a page:

<head>
    <base href="http://www.w3schools.com/images/" />
    <base target="_blank" />
</head>

<body>
    <img src="stickman.gif" />
    <a href="http://www.w3schools.com">W3Schools</a>
</body>

do not complicate what is simple!


added

from sitepoint

The basic element will be useful only to you if all your messages are relative links or will go to the same place.

+13

, http://:

$(function(){
    $('a').each(function() {
        $(this).attr('href', 'http://www.somesitename.com/filter' + this.href);
    });
});
+29

, href .

<base href="http://www.some-domain.com/" />
$("base").attr("href","http://www.some-other-domain.com/");
0

"/" href ,

$('a').each(function(){ var updated_link = $(this).attr('href').replace('blog/', ''); $(this).attr('href', updated_link); });

url.in ,

0

:

$(function(){
    $('a').attr('href', (n, old) => 'http://www.somesitename.com/filter' + old);
});

, .each this.href URL (: http://localhost:8888/mylink), : www.somesitename.com/filter/http://localhost:8888/mylink. , jQuery: $(this).attr('href'), /mylink.

0

You will probably need to use the append () function. jQuery has http://api.jquery.com/append/

-2
source

Source: https://habr.com/ru/post/1739096/


All Articles