如何向元素添加onload事件?

我可以使用:

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

对于这个吗?


当前回答

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

其他回答

我们可以使用MutationObserver来有效地解决这个问题,添加下面的示例代码

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style>
        #second{
            position: absolute;
            width: 100px;
            height: 100px;
            background-color: #a1a1a1;
        }
    </style>
</head>
<body>
<div id="first"></div>
<script>
    var callthis = function(element){
           element.setAttribute("tabIndex",0);
        element.focus();
        element.onkeydown = handler;
        function handler(){
                alert("called")
        }
    }


    var observer = new WebKitMutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            for (var i = 0; i < mutation.addedNodes.length; i++)
            if(mutation.addedNodes[i].id === "second"){
                callthis(mutation.addedNodes[i]);
            }

        })
    });
    observer.observe(document.getElementById("first"), { childList: true });


    var ele = document.createElement('div');
    ele.id = "second"

    document.getElementById("first").appendChild(ele);

</script>

</body>
</html>

我有同样的问题,并试图让一个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.

利用身体。通过属性(<body onload="myFn()“>…”)或者用Javascript绑定一个事件。这在jQuery中非常常见:

$(document).ready(function() {
    doSomething($('#myDiv'));
});

你可以使用onerror在IMG元素上自动触发一些js,而不使用src。

<img src onerror='alert()'>

使用iframe并隐藏它iframe就像一个body标签

<!DOCTYPE html>
<html>
<body>

<iframe style="display:none" onload="myFunction()" src="http://www.w3schools.com"></iframe>
<p id="demo"></p>

<script>
function myFunction() {
    document.getElementById("demo").innerHTML = "Iframe is loaded.";
}
</script>

</body>
</html>