使用事件委托观察具有特定类的元素或该元素的子元素的事件

发布于 2024-08-01 15:08:14 字数 731 浏览 2 评论 0原文

我有一个包含与此类似的元素的页面:

<div id='things'>
    <div class='thing'>
        <div class='activator'>
            <span>Some text</span>
        </div>
    </div>
</div>

代码与此类似:

$('things').observe(click, function(event) {
    var e = event.element();
    if (e.match('.activator')) {
        doSomeStuffWith(e);
    } else if (e.match('.activator *')) {
        doSomeStuffWith(e.up('.activator');
    }
});

因此,如果我单击 .activator 或其任何子元素,我想调用 .activator 上的函数,我只是想知道是否有没有某种方式组合两个 if 子句。 像 if (e.match('.class, .class *') { doStuff(e.upOrSelf('activator')); }

我想我可以用 upOrSelf 方法扩展 Element。但我不想这样做如果可能的话,任何非标准定制。

I have a page with elements similar to this:

<div id='things'>
    <div class='thing'>
        <div class='activator'>
            <span>Some text</span>
        </div>
    </div>
</div>

The code is similar to this:

$('things').observe(click, function(event) {
    var e = event.element();
    if (e.match('.activator')) {
        doSomeStuffWith(e);
    } else if (e.match('.activator *')) {
        doSomeStuffWith(e.up('.activator');
    }
});

So if I click the .activator or any of its child elements I want to call a function on the .activator, I'm just wondering if there isn't some way of combining the two if-clauses. Something like if (e.match('.class, .class *') { doStuff(e.upOrSelf('activator')); }

I guess I could extend the Element with an upOrSelf method. But I would prefer not to do any non-standard customizations if possible.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦里兽 2024-08-08 15:08:14

请参阅此处,了解有关更通用方法的讨论原型中的事件委托。 页面下方有一个 Event.delegate() 的实现,它使用一个小技巧来实现你想要的。 它收集目标元素及其祖先,并使用 Selector.matchElements 将事件侦听器应用于所有匹配元素。

它比这更复杂一些,但这里有一个缩写版本(未经测试):

$('things').observe('click', function(event) {
    var child = event.element();
    var ancestors = [child].concat(child.ancestors());
    Selector.matchElements(ancestors, '.activator').each(function(element) {
       doSomeStuffWith(element);
    });
})

See here for discussions about a more generic way to to event delegation in Prototype. Down the page there is an implementation of Event.delegate() which uses a little trick to achieve what you want. It gathers the target element and its ancestors and applies the event listener to all matching elements using Selector.matchElements.

It's a bit more complicated than this, but here is an abbreviated version (untested):

$('things').observe('click', function(event) {
    var child = event.element();
    var ancestors = [child].concat(child.ancestors());
    Selector.matchElements(ancestors, '.activator').each(function(element) {
       doSomeStuffWith(element);
    });
})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文