Javascript事件处理程序 - 为什么这样做?

时间:2015-05-01 00:15:49

标签: javascript events handler

我是javascript的新手,您可以从下面的代码中了解到。我想为页面上的6个按钮创建一个事件处理程序。单击按钮时,按钮下方的代码块的显示属性将改变为" none"到"阻止"。要做到这一点,我需要将每个按钮与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";
    }
}

0 个答案:

没有答案