简体   繁体   English

雄辩的javascript标签练习

[英]Eloquent javascript tabs exercise

Eloquent Javascript ch.14 exercise #3 answers, Making tabs. 雄辩的Java ch.14练习#3答案,制作制表符。

    <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)? 问题1:这看起来像一个简单的回调,为什么我不能简单地调用selectTab(i)?

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

Question 2: Why doesn't the function just return the selecTab function ie: 问题2:为什么函数不只返回selecTab函数,即:

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

Question 3: Why can't I pass an event object into selectTab like this? 问题3:为什么不能像这样将事件对象传递到selectTab中?

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! 可能并不雄辩,但我理解它并且有效!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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