有说服力的javascript选项卡练习
雄辩的Javascript第14章练习3答案,制作制表符有说服力的javascript选项卡练习,javascript,tabs,event-handling,eloquent,Javascript,Tabs,Event Handling,Eloquent,雄辩的Javascript第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> fu
<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>
问题1:这看起来像一个简单的回调,为什么我不能简单地调用selectTabi
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);
}
也许不是很有说服力,但我理解它,而且很有效 一,。这与时间有关:您需要函数延迟操作直到事件发生,而不是在绑定时触发。2.有很多种编码方式,谁知道为什么会选择这种方式。。。3.与1相关:在执行事件处理程序之前没有事件,因此需要一个事件处理程序函数。尽管如此,这似乎不是很有说服力;它使用旧的接口和太多的代码来做这么简单的事情。。。
button.addEventListener("click", function(event){ selectTab(event);});
function selectTab(event){
console.log(event.target.textContent);
}