如何向元素添加onload事件?

我可以使用:

<div onload="oQuickReply.swap();" ></div>

对于这个吗?


当前回答

不,你不能。使其工作的最简单的方法是将函数调用直接放在元素之后

例子:

...
<div id="somid">Some content</div>
<script type="text/javascript">
   oQuickReply.swap('somid');
</script>
...

或者-甚至更好-就在</body>前面:

...
<script type="text/javascript">
   oQuickReply.swap('somid');
</script>
</body>

...因此它不会阻止以下内容的加载。

其他回答

onload事件只能用于文档(主体)本身、帧、图像和脚本。换句话说,它只能附加到主体和/或每个外部资源。div不是外部资源,它是作为主体的一部分加载的,所以onload事件在那里不适用。

我只是想在这里补充一点,如果有人想在div的加载事件上调用函数&你不想使用jQuery(由于在我的情况下的冲突),那么只需在所有html代码或任何其他代码之后调用函数,包括函数代码和 简单地调用一个函数。

/* All Other Code*/
-----
------
/* ----At the end ---- */
<script type="text/javascript">
   function_name();
</script>

OR

/* All Other Code*/
-----
------
/* ----At the end ---- */
<script type="text/javascript">
 function my_func(){
   function definition;      

  }

 my_func();
</script>

避免使用任何基于间隔的方法(因为它们不是性能和准确的),并使用MutationObserver针对动态加载div的父div以获得更好的效率。

更新:这是我写的一个方便的函数。像这样使用它:

onElementLoaded("div.some_class").then(()=>{}).catch(()=>{});
/**
 *
 * Wait for an HTML element to be loaded like `div`, `span`, `img`, etc.
 * ex: `onElementLoaded("div.some_class").then(()=>{}).catch(()=>{})`
 * @param {*} elementToObserve wait for this element to load
 * @param {*} parentStaticElement (optional) if parent element is not passed then `document` is used
 * @return {*} Promise - return promise when `elementToObserve` is loaded
 */
function onElementLoaded(elementToObserve, parentStaticElement) {
  const promise = new Promise((resolve, reject) => {
    try {
      if (document.querySelector(elementToObserve)) {
        console.log(`element already present: ${elementToObserve}`);
        resolve(true);
        return;
      }
      const parentElement = parentStaticElement
        ? document.querySelector(parentStaticElement)
        : document;

      const observer = new MutationObserver((mutationList, obsrvr) => {
        const divToCheck = document.querySelector(elementToObserve);

        if (divToCheck) {
          console.log(`element loaded: ${elementToObserve}`);
          obsrvr.disconnect(); // stop observing
          resolve(true);
        }
      });

      // start observing for dynamic div
      observer.observe(parentElement, {
        childList: true,
        subtree: true,
      });
    } catch (e) {
      console.log(e);
      reject(Error("some issue... promise rejected"));
    }
  });
  return promise;
}


实现细节:

HTML:

<div class="parent-static-div">
  <div class="dynamic-loaded-div">
    this div is loaded after DOM ready event
  </div>
</div>

JS:

var observer = new MutationObserver(function (mutationList, obsrvr) {
  var div_to_check = document.querySelector(".dynamic-loaded-div"); //get div by class
  // var div_to_check = document.getElementById('div-id'); //get div by id

  console.log("checking for div...");
  if (div_to_check) {
    console.log("div is loaded now"); // DO YOUR STUFF!
    obsrvr.disconnect(); // stop observing
    return;
  }
});

var parentElement = document.querySelector("parent-static-div"); // use parent div which is already present in DOM to maximise efficiency
// var parentElement = document // if not sure about parent div then just use whole 'document'

// start observing for dynamic div
observer.observe(parentElement, {
  // for properties details: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserverInit
  childList: true,
  subtree: true,
});

我们可以在onload中使用所有这些标签

<body>, <frame>, <frameset>, <iframe>, <img>, <input type="image">, <link>, <script> and <style>

eg:

函数loadImage() { alert(“图像已加载”); } <img src="https://www.w3schools.com/tags/w3html.gif" onload="loadImage()" width="100" height="132">

不,你不能。使其工作的最简单的方法是将函数调用直接放在元素之后

例子:

...
<div id="somid">Some content</div>
<script type="text/javascript">
   oQuickReply.swap('somid');
</script>
...

或者-甚至更好-就在</body>前面:

...
<script type="text/javascript">
   oQuickReply.swap('somid');
</script>
</body>

...因此它不会阻止以下内容的加载。