简体   繁体   English

尽管有多个事件侦听器,但仅调用一次Javascript函数

[英]Javascript function called only once despite multiple event listeners

I am rebuilding one of my own websites specifically to avoid using jQuery since I used so little of it that the memory overhead just isn't necessary, and I'm not concerned about supporting older browsers (the version of Firefox I'm using is likely to be the oldest browser to ever look at my sites; so if they work in that they'll work for 99.99% of my audience). 我正在重建自己的网站之一,特别是为了避免使用jQuery,因为我只使用了很少的内容,因此不需要内存开销,而且我也不关心支持较旧的浏览器(我使用的Firefox版本是可能是有史以来查看我网站的最古老的浏览器;因此,如果它们能在我的网站上运行,它们将为我的受众群体提供99.99%的服务)。 I am encountering a problem when adding multiple event listeners to a few list items in the document. 将多个事件侦听器添加到文档中的几个列表项时遇到问题。

HTML snippet: HTML片段:

<div class="SubColumn LeftCol grid_12 alpha">
    <div class="InfoBox grid_12 alpha omega">
        <h1>Side Detail</h1>
        <ul>
            <li data-detail-item="Detail item" data-detail-info="Info about the detail item!">Detail item</li>
            <li data-detail-item="Detail item 2" data-detail-info="Info about the second detail item!">Detail item 2</li>
            <li>Detail item</li>
            <li>Detail item</li>
            <ul>
                <li>Detail item</li>
                <li>Detail item</li>
                <li>Detail item</li>
                <li>Detail item</li>
            </ul>
            <li>Detail item</li>
            <li>Detail item</li>
            <li>Detail item</li>
            <li>Detail item</li>
        </ul>
    </div>
</div>

Relevant Javascript: 相关的Javascript:

function PrepareDefBoxes()
{
    // I'm using document.querySelectorAll() here as a generic swiss army knife
    // I use it multiple times throughout the script
    // Quite frankly its CSS-selector-syntax input is easier for me to read & maintain
    // CSS-style selectors even work on the custom data-* global attributes ^_^
    var AllDeets = document.querySelectorAll("li[data-detail-item][data-detail-info]");
    // An array of events to add to all the details list items
    // Declared here because I *might* need to add more events; you never know~
    var Events = ["mouseover", "mouseout", "click"];

    // This is a coding trick I've used in C++ and in php
    // If you have nested for loops and all your code is in the innermost loop,
    // you can actually put them all on the same line or on successive lines,
    // then have the scoping braces following the innermost for loop :3
    for(var i = 0; i < AllDeets.length; i++)
    for(var e = 0; e < Events.length; e++)
    {
        AllDeets[i].addEventListener( Events[e], function(event) {
            DefBox(event.target);
        });
        console.log("Added " + Events[e] + " to " + AllDeets[i].innerHTML);
    }
}

function DefBox(ListItem)
{
    console.log("It works!");
}

The function PrepareDefBoxes() is called by an earlier Bootstrap() function that is itself invoked via an onload inline event listener on the document's body tag a la <body onload="Bootstrap()"> . 较早的Bootstrap()函数调用了PrepareDefBoxes()函数,该函数本身通过文档正文标签la <body onload="Bootstrap()">上的onload内联事件监听器调用。 When I refresh the page, I get this chunk of output logged to the console, exactly as expected: 刷新页面时,我完全按照预期将以下输出记录到控制台:

Added mouseover to Detail item
Added mouseout to Detail item
Added click to Detail item
Added mouseover to Detail item 2
Added mouseout to Detail item 2
Added click to Detail item 2

However, when I randomly mouse over and mouse out from the two list items that should have THREE event listeners bound to each of them, the function DefBox() is only ever called once! 但是,当我随机将鼠标悬停并从应该将三个事件侦听器绑定到它们的两个列表项上DefBox() ,函数DefBox()只会被调用一次! And it logs its output to the console only that once. 并且仅将其输出记录到控制台一次。 I don't even get extra output by clicking on the list items, either. 我什至没有通过单击列表项获得任何额外的输出。 When I move the cursor around over those two items, I should be getting a mess of "It works!" 当我将光标移到这两个项目上时,我会感到一团糟“它起作用了!” printed to the console. 打印到控制台。

I humbly request solutions that do not use jQuery, por favor! 我谦虚地要求使用jQuery的解决方案, 帮忙!

Your code works fine. 您的代码工作正常。 I would guess that you just misinterpreted the console output information. 我猜您只是误解了控制台输出信息。

See fiddle: https://jsfiddle.net/3h4y0t01/1/ (I've just made output more obvious): 参见小提琴: https : //jsfiddle.net/3h4y0t01/1/ (我刚刚使输出更加明显):

var counter = 0;
function DefBox(ListItem)
{
    document.getElementById('out').innerHTML = counter++;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM