如何向元素添加onload事件?
我可以使用:
<div onload="oQuickReply.swap();" ></div>
对于这个吗?
如何向元素添加onload事件?
我可以使用:
<div onload="oQuickReply.swap();" ></div>
对于这个吗?
当前回答
利用身体。通过属性(<body onload="myFn()“>…”)或者用Javascript绑定一个事件。这在jQuery中非常常见:
$(document).ready(function() {
doSomething($('#myDiv'));
});
其他回答
你不能在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>'
我们可以使用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>
由于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>
我非常喜欢用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
试试这个!永远不要在div上使用触发器两次!
您可以在div标记之前定义要调用的函数。
$(function(){
$('div[onload]').trigger('onload');
});
演示:杰斯菲德尔