作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如何为 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/
我是一名优秀的程序员,十分优秀!