gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 12:06:21 24 4
gpt4 key购买 nike

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

就像 ul 中的 li 列表一样,通过 JavaScript 添加。我需要用纯 JavaScript 来完成此操作。

最佳答案

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

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 向上搜索带有委托(delegate)的容器,以查看它是否是您的目标元素。

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

关于javascript - 如何为 JavaScript 附加 DOM 元素应用类似 live() 的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9198771/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com