如何向元素添加onload事件?

我可以使用:

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

对于这个吗?


当前回答

由于onload事件仅在少数元素上受支持,因此必须使用另一种方法。

你可以使用MutationObserver:

const trackElement = element => { let present = false; const checkIfPresent = () => { if (document.body.contains(element)) { if (!present) { console.log('in DOM:', element); } present = true; } else if (present) { present = false; console.log('Not in DOM'); } }; const observer = new MutationObserver(checkIfPresent); observer.observe(document.body, { childList: true }); checkIfPresent(); return observer; }; const element = document.querySelector('#element'); const add = () => document.body.appendChild(element); const remove = () => element.remove(); trackElement(element); <button onclick="add()">Add</button> <button onclick="remove()">Remove</button> <div id="element">Element</div>

其他回答

我只是想在这里补充一点,如果有人想在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>

当你从服务器加载一些html并将其插入DOM树时,你可以使用DOMSubtreeModified,但它已弃用-所以你可以使用MutationObserver或只是直接在loadElement函数中检测新内容,这样你就不需要等待DOM事件

var ignoreFirst=0; var observer = (new MutationObserver((m, ob)=> { if(ignoreFirst++>0) { console.log('Element add on', new Date()); } } )).observe(content, {childList: true, subtree:true }); // simulate element loading var tmp=1; function loadElement(name) { setTimeout(()=>{ console.log(`Element ${name} loaded`) content.innerHTML += `<div>My name is ${name}</div>`; },1500*tmp++) }; loadElement('Michael'); loadElement('Madonna'); loadElement('Shakira'); <div id="content"><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中使用所有这些标签

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

首先回答你的问题:不,你不能,不能直接这样做,就像你想做的那样。 也许现在回答有点晚,但这是我的解决方案,没有jQuery,纯javascript。 它最初是用来在DOM加载后和在keyup上应用一个调整文本区域大小的函数。

同样地,你可以用它来做一些(所有)div或只有一个,如果指定的话,像这样:

document.addEventListener("DOMContentLoaded", function() {
    var divs = document.querySelectorAll('div'); // all divs
    var mydiv = document.getElementById('myDiv'); // only div#myDiv
    divs.forEach( div => {
        do_something_with_all_divs(div);
    });
    do_something_with_mydiv(mydiv);
});

如果你真的需要在DOM加载后加载div,例如在ajax调用之后,你可以使用一个非常有用的hack,这很容易理解,你会发现它…working with-elements-before-the- DOM -is-ready....它说“在DOM准备好之前”,但它以同样的方式出色地工作,在ajax插入或js- appendchild -任何div之后。下面是代码,根据我的需要做了一些小更改。

css

.loaded { // I use only class loaded instead of a nodename
    animation-name: nodeReady;
    animation-duration: 0.001s;
}

@keyframes nodeReady {  
    from { clip: rect(1px, auto, auto, auto); }
    to { clip: rect(0px, auto, auto, auto); }  
}

javascript

document.addEventListener("animationstart", function(event) {
    var e = event || window.event;
    if (e.animationName == "nodeReady") {
        e.target.classList.remove('loaded');
        do_something_else();
    }
}, false);