实现jQuery的“live”与本机Javascript绑定 [英] Implementing jQuery's "live" binder with native Javascript

查看:91
本文介绍了实现jQuery的“live”与本机Javascript绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出如何将一个事件绑定到动态创建的元素。我需要事件来坚持该元素,即使它被破坏和重新生成。

I am trying to figure out how to bind an event to dynamically created elements. I need the event to persist on the element even after it is destroyed and regenerated.

显然,jQuery的现场功能很容易,但它们将如何用本机Javascript实现

Obviously with jQuery's live function its easy, but what would they look like implemented with native Javascript?

推荐答案

这是一个简单的例子:

function live(eventType, elementId, cb) {
    document.addEventListener(eventType, function (event) {
        if (event.target.id === elementId) {
            cb.call(event.target, event);
        }
    });
}

live("click", "test", function (event) {
    alert(this.id);
});

基本思想是要附加一个事件处理程序到文档,让事件起泡DOM。然后,检查 event.target 属性,看看它是否符合所需的条件(在这种情况下,只是 id

The basic idea is that you want to attach an event handler to the document and let the event bubble up the DOM. Then, check the event.target property to see if it matches the desired criteria (in this case, just that the id of the element).

编辑:

@shabunc 发现我的解决方案相当大的问题 - 小孩的事件元素将无法正确检测。解决这个问题的一个方法是查看祖先元素,看看是否有指定的 id

@shabunc discovered a pretty big problem with my solution-- events on child elements won't be detected correctly. One way to fix this is to look at ancestor elements to see if any have the specified id:

function live (eventType, elementId, cb) {
    document.addEventListener(eventType, function (event) {
        var el = event.target
            , found;

        while (el && !(found = el.id === elementId)) {
            el = el.parentElement;
        }

        if (found) {
            cb.call(el, event);
        }
    });
}

这篇关于实现jQuery的“live”与本机Javascript绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆