简体   繁体   中英

Eloquent javascript tabs exercise

Eloquent Javascript ch.14 exercise #3 answers, Making tabs.

    <div id="wrapper">
  <div data-tabname="one">Tab one</div>
  <div data-tabname="two">Tab two</div>
  <div data-tabname="three">Tab three</div>
</div>
<script>
  function asTabs(node) {
    var tabs = [];
    for (var i = 0; i < node.childNodes.length; i++) {
      var child = node.childNodes[i];
      if (child.nodeType == document.ELEMENT_NODE)
        tabs.push(child);
    }

    var tabList = document.createElement("div");
    tabs.forEach(function(tab, i) {
      var button = document.createElement("button");
      button.textContent = tab.getAttribute("data-tabname");
      button.addEventListener("click", function() { selectTab(i); });
      tabList.appendChild(button);
    });
    node.insertBefore(tabList, node.firstChild);

    function selectTab(n) {
      tabs.forEach(function(tab, i) {
        if (i == n)
          tab.style.display = "";
        else
          tab.style.display = "none";
      });
      for (var i = 0; i < tabList.childNodes.length; i++) {
        if (i == n)
          tabList.childNodes[i].style.background = "violet";
        else
          tabList.childNodes[i].style.background = "";
      }
    }
    selectTab(0);
  }
  asTabs(document.querySelector("#wrapper"));
</script>

Would someone mind explaining the significance of this line:

button.addEventListener("click", function() { selectTab(i); });

Question 1: This looks like a simple callback, why can't I simply place a call to selectTab(i)?

button.addEventListener("click", selectTab(n));

Question 2: Why doesn't the function just return the selecTab function ie:

button.addEventListener("click", function() { return selectTab(n); });

Question 3: Why can't I pass an event object into selectTab like this?

button.addEventListener("click", selectTab(event));
function selectTab(event){console.log(event.target)}

Thanks in advance!

Thanks dandavis. I was able to come up with this after your explanation:

button.addEventListener("click", function(event){ selectTab(event);});
function selectTab(event){
        console.log(event.target.textContent);
    }

Probably not eloquent, but I understand it and it works!

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