如何向元素添加onload事件?
我可以使用:
<div onload="oQuickReply.swap();" ></div>
对于这个吗?
如何向元素添加onload事件?
我可以使用:
<div onload="oQuickReply.swap();" ></div>
对于这个吗?
当前回答
您可以如下所示附加一个事件侦听器。当选择器#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
其他回答
我正在学习javascript和jquery,并通过所有的答案, 我在调用javascript函数加载div元素时遇到了同样的问题。 我尝试了$('<divid>').ready(function(){alert('test'}),它为我工作。我想知道这是一个好方法来执行onload调用div元素的方式,我使用jquery选择器。
谢谢
不,你不能。使其工作的最简单的方法是将函数调用直接放在元素之后
例子:
...
<div id="somid">Some content</div>
<script type="text/javascript">
oQuickReply.swap('somid');
</script>
...
或者-甚至更好-就在</body>前面:
...
<script type="text/javascript">
oQuickReply.swap('somid');
</script>
</body>
...因此它不会阻止以下内容的加载。
当你从服务器加载一些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>
试试这个!永远不要在div上使用触发器两次!
您可以在div标记之前定义要调用的函数。
$(function(){
$('div[onload]').trigger('onload');
});
演示:杰斯菲德尔
我有同样的问题,并试图让一个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.