如何向元素添加onload事件?
我可以使用:
<div onload="oQuickReply.swap();" ></div>
对于这个吗?
如何向元素添加onload事件?
我可以使用:
<div onload="oQuickReply.swap();" ></div>
对于这个吗?
当前回答
我们可以在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上添加事件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事件仅在少数元素上受支持,因此必须使用另一种方法。
你可以使用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>
onload事件只能用于文档(主体)本身、帧、图像和脚本。换句话说,它只能附加到主体和/或每个外部资源。div不是外部资源,它是作为主体的一部分加载的,所以onload事件在那里不适用。
我正在学习javascript和jquery,并通过所有的答案, 我在调用javascript函数加载div元素时遇到了同样的问题。 我尝试了$('<divid>').ready(function(){alert('test'}),它为我工作。我想知道这是一个好方法来执行onload调用div元素的方式,我使用jquery选择器。
谢谢
你可以使用一个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);