Eloquent Javascript 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:为什么我不能像这样将事件对象传递给selectab ?
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);
}
可能不是雄辩,但我理解它,它工作!