如何向元素添加onload事件?
我可以使用:
<div onload="oQuickReply.swap();" ></div>
对于这个吗?
如何向元素添加onload事件?
我可以使用:
<div onload="oQuickReply.swap();" ></div>
对于这个吗?
当前回答
我非常喜欢用YUI3库来做这类事情。
<div id="mydiv"> ... </div>
<script>
YUI().use('node-base', function(Y) {
Y.on("available", someFunction, '#mydiv')
})
见:http://developer.yahoo.com/yui/3/event/ onavailable
其他回答
试试这个。
. getelementbyid (" div ")。onload = alert("This is a div."); <div id="div">Hello World</div>
试试这个。你需要移除。从oQuickReply.swap()使函数工作。
. getelementbyid (" div ")。onload = oQuickReplyswap(); 函数oQuickReplyswap() { 警报(“Hello World”); } < div id = " div " > < / div >
我们可以使用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>
利用身体。通过属性(<body onload="myFn()“>…”)或者用Javascript绑定一个事件。这在jQuery中非常常见:
$(document).ready(function() {
doSomething($('#myDiv'));
});
由于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事件,它只支持下面列出的几个标签。
<body>, <frame>, <iframe>, <img>, <input type="image">, <link>, <script>, <style>
这里是onload事件的引用