如何向元素添加onload事件?
我可以使用:
<div onload="oQuickReply.swap();" ></div>
对于这个吗?
如何向元素添加onload事件?
我可以使用:
<div onload="oQuickReply.swap();" ></div>
对于这个吗?
当前回答
onload事件只能用于文档(主体)本身、帧、图像和脚本。换句话说,它只能附加到主体和/或每个外部资源。div不是外部资源,它是作为主体的一部分加载的,所以onload事件在那里不适用。
其他回答
当你从服务器加载一些html并将其插入DOM树时,你可以使用DOMSubtreeModified,但它已弃用-所以你可以使用MutationObserver或只是直接在loadElement函数中检测新内容,这样你就不需要等待DOM事件
var ignoreFirst=0; var observer = (new MutationObserver((m, ob)=> { if(ignoreFirst++>0) { console.log('Element add on', new Date()); } } )).observe(content, {childList: true, subtree:true }); // simulate element loading var tmp=1; function loadElement(name) { setTimeout(()=>{ console.log(`Element ${name} loaded`) content.innerHTML += `<div>My name is ${name}</div>`; },1500*tmp++) }; loadElement('Michael'); loadElement('Madonna'); loadElement('Shakira'); <div id="content"><div>
onload事件只能用于文档(主体)本身、帧、图像和脚本。换句话说,它只能附加到主体和/或每个外部资源。div不是外部资源,它是作为主体的一部分加载的,所以onload事件在那里不适用。
我非常喜欢用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加载一个滚动脚本,使用onload或load。我发现的问题是,它总是在Div打开之前工作,而不是在Div打开期间或之后,所以它不会真正工作。
然后我想出了这个方法。
<body>
<span onmouseover="window.scrollTo(0, document.body.scrollHeight);"
onmouseout="window.scrollTo(0, document.body.scrollHeight);">
<div id="">
</div>
<a href="" onclick="window.scrollTo(0, document.body.scrollHeight);">Link to open Div</a>
</span>
</body>
I placed the Div inside a Span and gave the Span two events, a mouseover and a mouseout. Then below that Div, I placed a link to open the Div, and gave that link an event for onclick. All events the exact same, to make the page scroll down to bottom of page. Now when the button to open the Div is clicked, the page will jump down part way, and the Div will open above the button, causing the mouseover and mouseout events to help push the scroll down script. Then any movement of the mouse at that point will push the script one last time.
我只是想在这里补充一点,如果有人想在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>