如何向元素添加onload事件?
我可以使用:
<div onload="oQuickReply.swap();" ></div>
对于这个吗?
如何向元素添加onload事件?
我可以使用:
<div onload="oQuickReply.swap();" ></div>
对于这个吗?
当前回答
使用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>
其他回答
我非常喜欢用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 >
我们可以在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">
onload事件只能用于文档(主体)本身、帧、图像和脚本。换句话说,它只能附加到主体和/或每个外部资源。div不是外部资源,它是作为主体的一部分加载的,所以onload事件在那里不适用。
我们可以使用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>