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

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

本文关键字:live 功能 应用 DOM JavaScript 元素      更新时间:2023-09-26

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

类似于通过JavaScript添加的ul中的li列表。我需要用简单的JavaScript来完成这项工作。

由于.live()只是一个事件委派,所以将处理程序放在离要添加的元素最近的元素上。

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一直搜索到具有委托的容器,以查看它是否是您的目标元素。

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


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

此外,你需要一个IE8的补丁,但这很容易。

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
        }
}

您必须将事件绑定到文档根,并检查event.target属性。如果它与给定的选择器匹配,则执行一些操作。

示例(假设addEventListener
示例:匹配id为test:的所有元素

var root = document.documentElement;
root.addEventListener('click', function(event) {
    var target = event.target;          // <-- Clicked element
    while (target && target !== root) { // Tree traversing
        if (target.id == 'test') {      // <------ Matches selector
            // Do something.
            break; // Optional: Stop traversal, because a match has been found
        }
        target = target.parentNode; // Go up in the tree
    }
}, true);

live()是jquery库的一个函数

  .live( events, handler(eventObject) )

events:包含JavaScript事件类型的字符串,例如"click"或"keydown"从jQuery 1.4开始,字符串可以包含多个空格分隔的事件类型或自定义事件名称。

handler(eventObject):在触发事件时执行的函数。

例如,当你在ul中创建li时,你必须活着才能捕获li,例如

$('li').live('mouseover',function(){
   alert('hello');
});

无论何时创建新元素,都可以手动附加事件处理程序。或者,您可以通过查看jQuery库并提取所需的部分来完全按照jQuery的方式进行操作。