如何向元素添加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>

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

其他回答

避免使用任何基于间隔的方法(因为它们不是性能和准确的),并使用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,
});

我有同样的问题,并试图让一个Div加载一个滚动脚本,使用onload或load。我发现的问题是,它总是在Div打开之前工作,而不是在Div打开期间或之后,所以它不会真正工作。

然后我想出了这个方法。

<body>

<span onmouseover="window.scrollTo(0, document.body.scrollHeight);" 
onmouseout="window.scrollTo(0, document.body.scrollHeight);">

<div id="">
</div>

<a href="" onclick="window.scrollTo(0, document.body.scrollHeight);">Link to open Div</a>

</span>
</body>

I placed the Div inside a Span and gave the Span two events, a mouseover and a mouseout. Then below that Div, I placed a link to open the Div, and gave that link an event for onclick. All events the exact same, to make the page scroll down to bottom of page. Now when the button to open the Div is clicked, the page will jump down part way, and the Div will open above the button, causing the mouseover and mouseout events to help push the scroll down script. Then any movement of the mouse at that point will push the script one last time.

这是一个非常简单的解决方案,100%有效。 在div中加载所有数据后,如果你想要执行javascript,只需在div或div的最后一行中加载<img>标记。 因为<img>标签支持onload事件,所以你可以很容易地调用javascript在这里如下:

<div>
<img onLoad="alert('Problem Solved');" src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" />
</div>

上图只显示了一个点(.),你甚至无法正常看到。 试一试。

你不能在div上添加事件onload,但你可以在文档加载时添加onkeydown并触发onkeydown事件

$(函数() { $(“.ccsdvCotentPS”).trigger(“onkeydown”); }); <script src=“https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js”></script> <div onkeydown=“setCss( );”> </div>'

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