如何向元素添加onload事件?

我可以使用:

<div onload="oQuickReply.swap();" ></div>

对于这个吗?


当前回答

利用身体。通过属性(<body onload="myFn()“>…”)或者用Javascript绑定一个事件。这在jQuery中非常常见:

$(document).ready(function() {
    doSomething($('#myDiv'));
});

其他回答

我们可以在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事件仅在少数元素上受支持,因此必须使用另一种方法。

你可以使用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>

我有同样的问题,并试图让一个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 id="somid">Some content</div>
<script type="text/javascript">
   oQuickReply.swap('somid');
</script>
...

或者-甚至更好-就在</body>前面:

...
<script type="text/javascript">
   oQuickReply.swap('somid');
</script>
</body>

...因此它不会阻止以下内容的加载。

我正在学习javascript和jquery,并通过所有的答案, 我在调用javascript函数加载div元素时遇到了同样的问题。 我尝试了$('<divid>').ready(function(){alert('test'}),它为我工作。我想知道这是一个好方法来执行onload调用div元素的方式,我使用jquery选择器。

谢谢