Thursday, February 22, 2018

[JavaScript][Exercise] Fix the bugs in the registerHandlers function


Fix the bugs in the registerHandlers function. An alert should display anchor's zero-based index within a document instead of following the link.

For example, in the document below, the alert should display "2" when Google anchor is clicked since it is the third anchor element in the document and its zero-based index is 2.
<body>
  In my life, I used the following web search engines:<br/>
  <a href="//www.yahoo.com">Yahoo!</a><br/>
  <a href="//www.altavista.com">AltaVista</a><br/>
  <a href="//www.google.com">Google</a><br/>
</body> 

Reference answer

We can't edit html code in this question! So we need to amend the html code by JavaScript, Set an attribute to store index of a tag, and call it in click event.
<html>
<body>
  In my life, I used the following web search engines:<br/>
  <a href="//www.yahoo.com">Yahoo!</a><br/>
  <a href="//www.altavista.com">AltaVista</a><br/>
  <a href="//www.google.com">Google</a><br/>
</body>
<script>
registerHandlers();
function registerHandlers() {
  var as = document.getElementsByTagName('a');
  for (var i = 0; i < as.length; i++) {
    as[i].setAttribute('data-index', i);
    as[i].onclick = function() {
      alert(this.getAttribute("data-index"));
      return false;
    }
  }
}
</script>
</html>
Reference
https://stackoverflow.com/questions/31632679/javascript-get-the-right-zero-based-index-of-clicked-link

No comments :

Post a Comment