如何为JavaScript附加的DOM元素应用类似live()的功能
How to apply live() like feature for JavaScript appended DOM elements
如何将类似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的方式进行操作。
相关文章:
- 添加文字和评论功能更新Div
- JavaScript打印功能使日历停止工作
- 使用Facebook live API创建实时视频对象时的隐私设置
- Ajax Live搜索发布到Laravel视图
- 每当您在选择器内移动鼠标时,悬停功能就会重复
- 如何防止网页加载后自动启动功能
- 除修剪外的其他功能
- 悬停功能触发器
- 使用angularjs向浏览器发送servlet响应(下载功能)
- 删除CKEditor工具栏按钮,但不删除功能
- 异步facebook功能
- 如何将chrome扩展功能移植到移动设备(特别是jquery和trello)
- jQuery滚动功能只工作一次
- Graphiti中是否有任何工具提示功能
- React redux初始化功能,无论状态变化如何
- 在哪里可以学习ECMAScript标准中尚未包含的JavaScript功能
- 当使用jquery live功能时,按钮将被触发两次
- 如何为JavaScript附加的DOM元素应用类似live()的功能
- Textarea不能与jQuery live keyup功能一起工作
- 更改为live或on时,单击功能不起作用