我刚接触JavaScript,如下面的代码所示。我想为页面上的6个按钮创建事件处理程序。单击按钮时,下面的代码块的显示属性从“none”更改为“block”。为此,我需要将每个按钮与一个唯一的HTML部分(在这种情况下为具有唯一ID的标签- pt1、pt2等)相关联。
我为此苦苦挣扎了一段时间,并让下面的代码工作。这就是问题所在!事实证明,我完全错了。但是,作为新手,当它起作用时,我认为我正在做正确的事情。由于我花了几个小时在这上面,我需要知道为什么下面的代码可以工作(这样我会感到我学到了东西)。我将突出显示我自己无法理解为什么它能工作的代码部分。
var buttons = document.getElementsByClassName("CSS");
for (var i = 0; i < buttons.length; i++) {
// Generate strings associated with the button ids and the event handlers for each button
var buttonID = "button" + i;
var clickHandlerID = "clickHandler" + i;
var buttonEH = document.getElementById(buttonID);
// Identify the button elements by id
// As clickHandlerID is a string, to get the browser to recognise it as a function name
var clickHandler = window[clickHandlerID];
buttonEH.addEventListener("click", clickHandler, false);
}
/*****************************************************************************/
// Why does this work?
// clickHandler1, clickHandler2, etc are not referenced in my event handler.
// My botched attempt to create them in the event handler (var clickHandler = window[clickHandlerID];)
// resulted in "undefined" values (from console.log(clickHandler)).
// Yet it worked?!?! (I did eventually find the correct approach, a simple 10 line solution,
// but I am troubled that I don't understand what is going on here. Any help would be greatly appreciated!!)
/*****************************************************************************/
function clickHandler1 () {
if (pt1.style.display === "block") {
pt1.style.display = "none";
} else {
pt1.style.display = "block";
}
}
function clickHandler2 () {
if (pt2.style.display === "block") {
pt2.style.display = "none";
} else {
pt2.style.display = "block";
}
}