• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

为JavaScript追加的DOM元素应用live:类的功能

用户头像
it1352
帮助1

问题说明

如何应用 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.

正确答案

#1

由于 .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
        }
}

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfkeik
系列文章
更多 icon
同类精品
更多 icon
继续加载