简体   繁体   中英

How to handle an indefinite number of events?

So say I have some code that creates an indefinite number of comments in a main section of the page, such as

function createcomments(comments) {
    var main = document.getElementById("main");
    for (var i = 0; i < comments.length; i++) {
        var comment = document.createElement("quoteblock");
        comment.innerHTML = comments[i];
        main.appendChild(comment);
        comment.classList.add("comment");
    }
}

And every time a visitor to my page hovered over a comment the background would turn red or something:

window.onload = function() {
    var comments = document.querySelectorAll(".comment");
    // code for handling .onmouseover and .onmouseout
    // for each element in the array
}

How would I do that? I think there is a way to do it with jQuery, but I was wondering if there's a way to do it with JavaScript.

In jQuery there are this two helper functions delegate() and live() . They work as nicely described in this blog post.

Actually you can attach an eventHandler to a parent element that is than listeing to all mouse events (and other events). Using delegation you then check on the parent elements eventHandler if the event is coming from a specific child.

<ul>
    <li>one</li>
    <li>two</li>
    <li>three</li>
</ul>

here we add some simple html, but we dont attach to the span element for a click handler, but to the div. in the div eventHandler we then check, what target actually got clicked

var divs = document.querySelector("ul");
divs.addEventListener("click", function(ev) {
   if (ev.target.tagName === "LI")
       console.log("A list element  (" + ev.target.innerText + ") was clicked");
});

The whole reason behind this delegation is performance. also, if you remove or add items dynamically, the event handling works as expected without any additional work.

If you dont want to use the whole jQuery for this simple step, I still suggest you use some framework, as it is always better to use community support than reinventing the wheel

try http://craig.is/riding/gators , looks nice :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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