简体   繁体   中英

Redirect when all links have been clicked?

I have a page with three hashtag urls:

<a href="#Link1">Some Text 1</a>
<a href="#Link2">Some Text 2</a>
<a href="#Link3">Some Text 3</a>

Once the user has clicked all three I need to redirect them to another URL.

Does anyone have an example, or know a way I can do this?

Try with this:

window.onload = function () {
    var anchors, clicked_count, clicked, i, cur_anchor, my_anchor_id;

    anchors = document.getElementsByTagName("a");
    clicked_count = 0;
    clicked = {};

    for (i = 0; i < anchors.length; i++) {
        cur_anchor = anchors[i];
        cur_anchor.setAttribute("data-anchor-id", i);
        cur_anchor.onclick = function (e) {
            e = e || window.event;
            e.preventDefault();

            my_anchor_id = this.getAttribute("data-anchor-id");
            if (!(my_anchor_id in clicked)) {
                clicked[my_anchor_id] = null;
                if (++clicked_count === anchors.length) {
                    console.log("WOULD BE REDIRECTING");
                    //window.location.href = "NEW URL";
                }
            }
        };
    }
};

DEMO: http://jsfiddle.net/hCRtD/1/

To prove the demo works, click on some anchors several times before clicking on the last one needed. It won't just complete after 3 clicks total (my original solution was flawed that way), but will wait until each are clicked at least once.

It sets a special attribute on all <a> tags, uniquely identifying them. Obviously, an id could be used, but you didn't include it and it's easy enough to do this way.

Then, when an anchor is clicked (only its first time), its unique identifier is added to a collection ( clicked ).

When a counter ( clicked_count ), which is incremented every time an anchor is clicked for the first time, reaches the total number of anchors found in the first place, then everything has completed.

Add html class:

<a href="#Link1" class="redirect">Some Text 1</a>
<a href="#Link2" class="redirect">Some Text 2</a>
<a href="#Link3" class="redirect">Some Text 3</a>

And try javascript:

function catchAnchors(){
  var links = document.getElementsByClassName("redirect");//get your links
  for(var i=links.length-1;i>=0;i--){
   if(!links[i].wasClick)return;//if never clicked return;
  }
   location.href = "your url";//redirect
}

var links = document.getElementsByClassName("redirect");//get your links
for(var i=links.length-1;i>=0;i--){
  links[i].onclick = function(){
    this.wasClick = true;//set mark onclick event
    catchAnchors();//check links
  }
}

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