使用 JQuery,是否可以在 DOM 元素调用 .remove() 时运行函数?
正如问题所述,我试图做的是有一个函数,当从 DOM 中删除 DOM 元素时调用该函数,就像析构函数一样。
我研究了卸载,但根据我的理解,只有当浏览器导航离开页面时才会调用。
提前致谢!
As the question states, what I'm attempting to do is have a function that is called when a DOM element is removed from the DOM, much like a destructor.
I looked into unload, but from my understanding that's only called when the browser navigates away from the page.
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
可以使用特殊事件 建立移除跟踪。我创建了一个示例,它允许绑定到
removed
事件。请注意,此方法仅在 jQuery 发起删除时有效(例如调用$(…).remove()
)。对于更通用的解决方案,请使用 DOMNodeRemoved ,但这在 IE 中不起作用。要启用对元素的跟踪,请调用
$(…).trackRemoval()
,当您删除该元素或其父元素之一时,该元素将触发removed
事件。jsFiddle 包含使用示例代码。
It is possible to use the special events to build removal tracking. I've created an example that allows to bind to an
removed
event. Note that this approach only works when the removal is initiated by jQuery (calling$(…).remove()
) for example. For a more general solution useDOMNodeRemoved
but that wouldn't work in IE.To enable tracking for an element call
$(…).trackRemoval()
and the element will fire aremoved
event when you remove it or one of its parents.The jsFiddle contains sample code for usage.
我不知道这是不是你要找的。不是很漂亮的代码,只是为了展示我想使用的内容:
当然有基于直接观察 DOM 的解决方案,但问题是浏览器兼容性。您可能应该查看 突变事件。
I don't know if it's that what you're looking for. Not really pretty code, just to show what I would like to use:
There are of course solutions based on watching the DOM directly but the problem is the browser compatibility. You should probably check out mutation events.
试试这个:
用法:
请参阅 http://jsfiddle.net/alnitak/25Pnn/ 的工作示例
Try this:
usage:
See a working example at http://jsfiddle.net/alnitak/25Pnn/
您始终可以重载删除函数(所有 JavaScript 对象都可以在运行时动态更改)并将其替换为您自己的函数,该函数会触发一个事件,您可以使用该事件来响应删除。
You could always Overload the Remove function (all javascript objects can be dynamically changes in runtime) and replace it with your own function that triggers an event you can use to react to remove.