为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
}
}
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tanhcfkeik
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
希伯来语的空格句子标记化错误
it1352 06-22 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20