简体   繁体   English

如何处理不确定的事件?

[英]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. 我认为有一种使用jQuery的方法,但是我想知道是否有一种使用JavaScript的方法。

In jQuery there are this two helper functions delegate() and live() . 在jQuery中,有这两个辅助函数delegate()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). 实际上,您可以将eventHandler附加到父元素,而不是列出所有鼠标事件(和其他事件)。 Using delegation you then check on the parent elements eventHandler if the event is coming from a specific child. 然后使用委托,检查父元素eventHandler是否事件来自特定的子项。

<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. 在这里,我们添加了一些简单的html,但是我们没有将其附加到click处理程序的span元素上,而是附加到了div上。 in the div eventHandler we then check, what target actually got clicked 然后在div eventHandler中检查实际点击了哪个目标

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. delegation背后的全部原因是业绩。 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 如果您不想在整个简单步骤中使用整个jQuery,我仍然建议您使用一些框架,因为使用社区支持总是比重新发明轮子更好。

try http://craig.is/riding/gators , looks nice :) 尝试http://craig.is/riding/gators ,看起来不错:)

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

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