如何监听要加载的特定元素?

发布于 2024-10-03 05:00:39 字数 567 浏览 0 评论 0原文

是否可以监听要加载的特定 DOM 元素?我有一个在整个页面加载时调用的 window.onload 事件,但我正在寻找一种方法来为加载的每个 DOM 元素调用它。 (onload 不会冒泡吗?)

示例:

function init() {
  alert(this.id); // Should be in context of DOM element that bubbled up when loaded
}
window.onload = init;
<div id="one">One</div>
<div id="two">One</div>
<div id="three">One</div>

我希望这段代码能够提醒一、二、三。

Is it possible to listen for a specific DOM element to be loaded? I have a window.onload event that is called when the whole page loads, but I'm looking for a way for it to be called for each DOM element that gets loaded. (Does onload not bubble up?)

Example:

function init() {
  alert(this.id); // Should be in context of DOM element that bubbled up when loaded
}
window.onload = init;
<div id="one">One</div>
<div id="two">One</div>
<div id="three">One</div>

I want this code to alert one, two, three.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

可可 2024-10-10 05:00:39

onload 事件不会像这样冒泡,这里有 2 个选项:

  1. 轮询元素,按时间间隔对其进行检查。
  2. 使用 DOM 突变事件(因浏览器而异 - 主要是 IE 实现问题)来监听,尽管这会很昂贵,因为您必须过滤除元素之外的所有内容。

onload events don't bubble like this, you have 2 options here:

  1. poll for the element, running a check for it on an interval.
  2. use DOM mutation events (which vary across browsers - mainly IE implementation headaches) to listen, though this will be expensive, since you'll have to filter everything other than your element.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文