开发者

How to listen for specific elements to load?

开发者 https://www.devze.com 2023-01-25 22:31 出处:网络
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 ele

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="o开发者_运维知识库ne">One</div>
<div id="two">One</div>
<div id="three">One</div>

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


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.
0

精彩评论

暂无评论...
验证码 换一张
取 消