change domain portion of links with javascript or jquery

风流意气都作罢 提交于 2019-12-19 09:55:09

问题


Sorry for my original question being unclear, hopefully by rewording I can better explain what I want to do.

Because of this I need a way to use JavaScript (or jQuery) to do the following:

  • determine domain of the current page being accessed
  • identify all the links on the page that use the domain www.domain1.com and replace with www.domain2.com

i.e. if the user is accessing www.domain2.com/index then:

<a href="www.domain1.com/contentpages/page.html">Test 1</a>

should be rewritten dynamically on load to

<a href="www.domain2.com/contentpages/page.html">Test 1</a>

Is it even possible to rewrite only a portion of the url in an href tag?


回答1:


Your code will loop over all links on the page. Here's a version that only iterates over URLS that need to be replaced.

var linkRewriter = function(a, b) {
    $('a[href*="' + a + '"]').each(function() {
        $(this).attr('href', $(this).attr('href').replace(a, b));
    });
};

linkRewriter('originalDomain.com', 'rewrittenDomain.com');



回答2:


I figured out how to make this work.

<script type="text/javascript"> 
// link rewriter
$(document).ready (
    function link_rewriter(){ 
        var hostadd = location.host;
        var vendor = '999.99.999.9';
        var localaccess = 'somesite1.';

        if (hostadd == vendor) { 
            $("a").each(function(){
                var o = $(this);
                var href = o.attr('href');
                var newhref;
                newhref = href.replace(/somesite1/i, "999.99.999.99");
                o.attr('href',newhref);
            });
        }
    }
);
</script>



回答3:


You'll need to involve Java or something server-side to get the IP address. See this:

http://javascript.about.com/library/blip.htm



来源:https://stackoverflow.com/questions/7449480/change-domain-portion-of-links-with-javascript-or-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!