如何向元素添加onload事件?

我可以使用:

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

对于这个吗?


当前回答

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

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

其他回答

你可以使用一个interval来检查它,直到它像这样加载: https://codepen.io/pager/pen/MBgGGM

let checkonloadDoSomething = setInterval(() => {
  let onloadDoSomething = document.getElementById("onloadDoSomething");
  if (onloadDoSomething) {
    onloadDoSomething.innerHTML="Loaded"
    clearInterval(checkonloadDoSomething);
  } else {`enter code here`
    console.log("Waiting for onloadDoSomething to load");
  }
}, 100);

我只是想在这里补充一点,如果有人想在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来有效地解决这个问题,添加下面的示例代码

<!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>

您可以如下所示附加一个事件侦听器。当选择器#my-id的div完全加载到DOM时,它就会触发。

$(document).on('EventName', '#my-id', function() {
 // do something
});

在本例中,EventName可以是'load'或'click'

https://api.jquery.com/on/#on-events-selector-data-handler

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

例子:

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

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

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

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