簡體   English   中英

雄辯的javascript標簽練習

[英]Eloquent javascript tabs exercise

雄辯的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>

有人介意解釋此行的重要性嗎?

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

問題1:這看起來像一個簡單的回調,為什么我不能簡單地調用selectTab(i)?

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

問題2:為什么函數不只返回selecTab函數,即:

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

問題3:為什么不能像這樣將事件對象傳遞到selectTab中?

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

提前致謝!

謝謝丹達維斯。 經過您的解釋,我得以提出以下建議:

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

可能並不雄辯,但我理解它並且有效!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM