Implementing jQuery#39;s quot;livequot; binder with native Javascript(实现 jQuery 的“live带有本机 Javascript 的活页夹)
问题描述
我试图弄清楚如何将事件绑定到动态创建的元素.即使在元素被销毁和重新生成后,我也需要该事件在元素上持续存在.
I am trying to figure out how to bind an event to dynamically created elements. I need the event to persist on the element even after it is destroyed and regenerated.
显然使用 jQuery 的 live 函数很容易,但是使用原生 Javascript 实现它们会是什么样子?
Obviously with jQuery's live function its easy, but what would they look like implemented with native Javascript?
推荐答案
这是一个简单的例子:
function live(eventType, elementId, cb) {
document.addEventListener(eventType, function (event) {
if (event.target.id === elementId) {
cb.call(event.target, event);
}
});
}
live("click", "test", function (event) {
alert(this.id);
});
基本思想是您希望将事件处理程序附加到文档并让事件在 DOM 中冒泡.然后,检查 event.target
属性以查看它是否符合所需条件(在本例中,就是元素的 id
).
The basic idea is that you want to attach an event handler to the document and let the event bubble up the DOM. Then, check the event.target
property to see if it matches the desired criteria (in this case, just that the id
of the element).
@shabunc 发现了一个很大的问题使用我的解决方案 - 无法正确检测到子元素上的事件.解决此问题的一种方法是查看祖先元素以查看是否有指定的 id
:
@shabunc discovered a pretty big problem with my solution-- events on child elements won't be detected correctly. One way to fix this is to look at ancestor elements to see if any have the specified id
:
function live (eventType, elementId, cb) {
document.addEventListener(eventType, function (event) {
var el = event.target
, found;
while (el && !(found = el.id === elementId)) {
el = el.parentElement;
}
if (found) {
cb.call(el, event);
}
});
}
这篇关于实现 jQuery 的“live"带有本机 Javascript 的活页夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:实现 jQuery 的“live"带有本机 Javascript 的活页夹


基础教程推荐
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01