如何为JavaScript追加的DOM元素应用live()之类的功能 [英] How to apply live() like feature for JavaScript appended DOM elements

查看:38
本文介绍了如何为JavaScript追加的DOM元素应用live()之类的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何应用 live()类似JavaScript附加DOM元素的功能?

How to apply live() like feature for JavaScript appended DOM elements?

li ul 里面的列表,它是通过JavaScript添加的。我需要在纯JavaScript中执行此操作。

Like a li list inside ul which is added through JavaScript. I need to do this in plain JavaScript.

推荐答案

由于 .live()只是事件委托,将处理程序放在最接近要添加的元素上。

Since .live() is simply event delegation, place your handler on the nearest element to the ones being added.

var container = document.getElementById('my_container');

container.onclick = function(e) {
    e = e || window.event;
    var target = e.target || e.srcElement;

    while(target && target.nodeName.toUpperCase() !== 'LI' ) {
        if( target === this )
            target = null;
        else 
            target = target.parentNode;
    }

    if( target ) {
        // work with the LI
    }
};

这也类似于 .live()从某种意义上说,它从 e.target 搜索到具有委托的容器,看它是否是你的目标元素。

This is also similar to .live() in the sense that it searches from the e.target up to the container with the delegate to see if it is your targeted element.

如果 li 有后代,只测试 e.target 本身是不够的。

Just testing the e.target itself isn't enough if the li has descendants.

对于元素的更复杂分析,您可以使用 .matchesSelector ,虽然您需要在正确的名称下将其粘贴在 HTMLElement.prototype 上,因为大多数浏览器都将其作为扩展名包含在内。

For more complex analysis of the elements, you could use .matchesSelector, though you'd need to stick it on the HTMLElement.prototype under the correct name, since most browsers include it as an extension.

另外,你需要一个IE8补丁,但这很简单。

Also, you'd need a patch for IE8, but that's pretty easy.

if (HTMLElement) {
    if (!HTMLElement.prototype.matches && !HTMLElement.prototype.matchesSelector) {
        HTMLElement.prototype.matches =
        HTMLELement.prototype.matchesSelector = 
            HTMLElement.prototype.webkitMatchesSelector ||
            HTMLElement.prototype.mozMatchesSelecvtor ||
            HTMLElement.prototype.msMatchesSelector ||
            HTMLElement.prototype.oMatchesSelector;
    }
} else if (!Element.prototype.matchesSelector && Element.prototype.querySelectorAll) {

    Element.prototype.matches = 
    Element.prototype.matchesSelector =
        function() {
            // exercise for reader to implement using .querySelectorAll, 
            //    though it's pretty easy, and available online if you search
        }
}

这篇关于如何为JavaScript追加的DOM元素应用live()之类的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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