如何向元素添加onload事件?
我可以使用:
<div onload="oQuickReply.swap();" ></div>
对于这个吗?
如何向元素添加onload事件?
我可以使用:
<div onload="oQuickReply.swap();" ></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>
其他回答
我们可以使用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>
试试这个。
. 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 >
试试这个!永远不要在div上使用触发器两次!
您可以在div标记之前定义要调用的函数。
$(function(){
$('div[onload]').trigger('onload');
});
演示:杰斯菲德尔
我只是想在这里补充一点,如果有人想在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>
您可以如下所示附加一个事件侦听器。当选择器#my-id的div完全加载到DOM时,它就会触发。
$(document).on('EventName', '#my-id', function() {
// do something
});
在本例中,EventName可以是'load'或'click'
https://api.jquery.com/on/#on-events-selector-data-handler