简体   繁体   中英

How to redirect any specific link on the page to a specific url?

How to redirect any specific link on the page to a specific url?

I have a webpage and it contains several links.

  • link1.com (20 links)
  • link2.com (15 links)
  • link3.com (8 links)

I want that whenever someone clicks on link1.com he gets redirected to www.example.com

Please advise how I can acheieve this.

With the below code I can do a redirect for a current page on screen. But I need to do it for every link on my website.

Here is some sample code. You can edit the redirects variable to match your needs. The index of the redirects variable is a regular expression, if it matches the link gets redirected.

option 1

<a href="http://link1.com">link 1</a>
<a href="http://link2.com/alsoredirected">link 2</a>
<a href="http://wikipedia.org">not redirected</a>

<script>
var aTags = document.getElementsByTagName("a");
var redirects = {
    "http://link1.com": "http://google.com",
    "link2.com": "http://google.com"
};

for(var i = 0;i < aTags.length; i++) {
    aTags[i].addEventListener("click", function(event) {
        var url = this.getAttribute("href");

        for (var redirect in redirects) {
            var pattern = new RegExp(redirect);

            if (pattern.test(url)) {
                window.location = redirects[redirect];
                event.preventDefault();
            }
        }
    });
}
</script>

option 2

This is the preferred solution as it replaces the href attribute if necessary. Thus you do not have to check the redirects on every click.

<a href="http://link1.com">link 1</a>
<a href="http://link2.com/alsoredirected">link 2</a>
<a href="http://wikipedia.org">not redirected</a>

<script>
var aTags = document.getElementsByTagName("a");
var redirects = {
    "http://link1.com": "http://google.com",
    "link2.com": "http://google.com"
};

for(var i = 0;i < aTags.length; i++) {
    var url = aTags[i].getAttribute("href");

    for (var redirect in redirects) {
        var pattern = new RegExp(redirect);

        if (pattern.test(url)) {
            aTags[i].setAttribute("href", redirects[redirect]);
        }
    }
}
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM