Javascript 如何将 onload 事件添加到 div 元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4057236/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add onload event to a div element
提问by monkey_boys
How do you add an onload
event to an element?
如何onload
向元素添加事件?
Can I use:
我可以用吗:
<div onload="oQuickReply.swap();" ></div>
for this?
为了这?
回答by DanMan
No, you can't. The easiest way to make it work would be to put the function call directly after the element
不,你不能。使其工作的最简单方法是将函数调用直接放在元素之后
Example:
例子:
...
<div id="somid">Some content</div>
<script type="text/javascript">
oQuickReply.swap('somid');
</script>
...
or - even better - just in front of </body>
:
或者 - 甚至更好 - 就在</body>
:
...
<script type="text/javascript">
oQuickReply.swap('somid');
</script>
</body>
...so it doesn't block the following content from loading.
...所以它不会阻止加载以下内容。
回答by kijin
The onload
event can only be used on the document(body)
itself, frames, images, and scripts. In other words, it can be attached to only body and/or each external resource. The div is not an external resource and it's loaded as part of the body, so the onload
event doesn't apply there.
该onload
事件只能在使用document(body)
本身,帧,图像和脚本。换句话说,它只能附加到 body 和/或每个外部资源。div 不是外部资源,它作为主体的一部分加载,因此该onload
事件不适用于那里。
回答by John Williams
You can trigger some js automatically on an IMG element using onerror, and no src.
您可以使用 onerror 在 IMG 元素上自动触发一些 js,而无需使用 src。
<img src onerror='alert()'>
回答by Samda
onload event it only supports with few tags like listed below.
onload 事件它只支持下面列出的几个标签。
<body>, <frame>, <iframe>, <img>, <input type="image">, <link>, <script>, <style>
Here the reference for onload event
这里是onload 事件的参考
回答by Kuofp
回答by dev_khan
I just want to add here that if any one want to call a function on load event of div & you don't want to use jQuery(due to conflict as in my case) then simply call a function after all the html code or any other code you have written including the function code and simply call a function .
我只想在这里补充一点,如果有人想在 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>
回答by user2364729
we can use MutationObserver to solve the problem in efficient way adding a sample code below
我们可以使用 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>
回答by Rounin
In November 2019, I am seeking a way to create a (hypothetical) onparse
EventListener
for <elements>
which don't take onload
.
十一月2019年,我寻求一种方法来创建一个(假设的)onparse
EventListener
对于<elements>
不拿onload
。
The (hypothetical) onparse
EventListener
must be able to listen for when an element is parsed.
(假设)onparse
EventListener
必须能够在解析元素时侦听。
Third Attempt (and Definitive Solution)
第三次尝试(和最终解决方案)
I was pretty happy with the Second Attemptbelow, but it just struck me that I can make the code shorter and simpler, by creating a tailor-made event:
我对下面的第二次尝试非常满意,但让我震惊的是,我可以通过创建一个量身定制的事件来使代码更短更简单:
let parseEvent = new Event('parse');
This is the best solution yet.
这是迄今为止最好的解决方案。
The example below:
下面的例子:
- Creates a tailor-made
parse
Event
- Declares a function (which can be run at
window.onload
or any time) which:- Finds any elements in the document which include the attribute
data-onparse
- Attaches the
parse
EventListener
to each of those elements - Dispatches the
parse
Event
to each of those elements to execute theCallback
- Finds any elements in the document which include the attribute
- 打造量身定制的
parse
Event
- 声明一个函数(可以在
window.onload
任何时候运行),它:- 查找文档中包含该属性的任何元素
data-onparse
- 将 附加
parse
EventListener
到每个元素 - 将 分
parse
Event
发给这些元素中的每一个以执行Callback
- 查找文档中包含该属性的任何元素
Working Example:
工作示例:
// Create (homemade) parse event
let parseEvent = new Event('parse');
// Create Initialising Function which can be run at any time
const initialiseParseableElements = () => {
// Get all the elements which need to respond to an onparse event
let elementsWithParseEventListener = document.querySelectorAll('[data-onparse]');
// Attach Event Listeners and Dispatch Events
elementsWithParseEventListener.forEach((elementWithParseEventListener) => {
elementWithParseEventListener.addEventListener('parse', updateParseEventTarget, false);
elementWithParseEventListener.dataset.onparsed = elementWithParseEventListener.dataset.onparse;
elementWithParseEventListener.removeAttribute('data-onparse');
elementWithParseEventListener.dispatchEvent(parseEvent);
});
}
// Callback function for the Parse Event Listener
const updateParseEventTarget = (e) => {
switch (e.target.dataset.onparsed) {
case ('update-1') : e.target.textContent = 'My First Updated Heading'; break;
case ('update-2') : e.target.textContent = 'My Second Updated Heading'; break;
case ('update-3') : e.target.textContent = 'My Third Updated Heading'; break;
case ('run-oQuickReply.swap()') : e.target.innerHTML = 'This <code><div></code> is now loaded and the function <code>oQuickReply.swap()</code> will run...'; break;
}
}
// Run Initialising Function
initialiseParseableElements();
let dynamicHeading = document.createElement('h3');
dynamicHeading.textContent = 'Heading Text';
dynamicHeading.dataset.onparse = 'update-3';
setTimeout(() => {
// Add new element to page after time delay
document.body.appendChild(dynamicHeading);
// Re-run Initialising Function
initialiseParseableElements();
}, 3000);
div {
width: 300px;
height: 40px;
padding: 12px;
border: 1px solid rgb(191, 191, 191);
}
h3 {
position: absolute;
top: 0;
right: 0;
}
<h2 data-onparse="update-1">My Heading</h2>
<h2 data-onparse="update-2">My Heading</h2>
<div data-onparse="run-oQuickReply.swap()">
This div hasn't yet loaded and nothing will happen.
</div>
Second Attempt
第二次尝试
The First Attemptbelow (based on @JohnWilliams
' brilliant Empty Image Hack) used a hardcoded <img />
and worked.
下面的第一次尝试(基于@JohnWilliams
“出色的空图像黑客”)使用了硬编码<img />
并有效。
I thought it ought to be possible to remove the hardcoded <img />
entirely and only dynamically insert it after detecting, in an element which needed to fire an onparse
event, an attribute like:
我认为应该可以<img />
完全删除硬编码,并且只有在检测到需要触发onparse
事件的元素中的属性后才动态插入它,例如:
data-onparse="run-oQuickReply.swap()"
It turns out, this works very well indeed.
事实证明,这确实非常有效。
The example below:
下面的例子:
- Finds any elements in the document which include the attribute
data-onparse
- Dynamically generates an
<img src />
and appends it to the document, immediately after each of those elements - Fires the
onerror
EventListener
when the rendering engine parses each<img src />
- Executes the
Callback
andremoves that dynamically generated<img src />
from the document
- 查找文档中包含该属性的任何元素
data-onparse
- 动态生成 an
<img src />
并将其附加到文档中,紧跟在每个元素之后 - 火灾
onerror
EventListener
时的渲染引擎解析每个<img src />
- 执行
Callback
并删除<img src />
从文档中动态生成的
Working Example:
工作示例:
// Get all the elements which need to respond to an onparse event
let elementsWithParseEventListener = document.querySelectorAll('[data-onparse]');
// Dynamically create and position an empty <img> after each of those elements
elementsWithParseEventListener.forEach((elementWithParseEventListener) => {
let emptyImage = document.createElement('img');
emptyImage.src = '';
elementWithParseEventListener.parentNode.insertBefore(emptyImage, elementWithParseEventListener.nextElementSibling);
});
// Get all the empty images
let parseEventTriggers = document.querySelectorAll('img[src=""]');
// Callback function for the EventListener below
const updateParseEventTarget = (e) => {
let parseEventTarget = e.target.previousElementSibling;
switch (parseEventTarget.dataset.onparse) {
case ('update-1') : parseEventTarget.textContent = 'My First Updated Heading'; break;
case ('update-2') : parseEventTarget.textContent = 'My Second Updated Heading'; break;
case ('run-oQuickReply.swap()') : parseEventTarget.innerHTML = 'This <code><div></code> is now loaded and the function <code>oQuickReply.swap()</code> will run...'; break;
}
// Remove empty image
e.target.remove();
}
// Add onerror EventListener to all the empty images
parseEventTriggers.forEach((parseEventTrigger) => {
parseEventTrigger.addEventListener('error', updateParseEventTarget, false);
});
div {
width: 300px;
height: 40px;
padding: 12px;
border: 1px solid rgb(191, 191, 191);
}
<h2 data-onparse="update-1">My Heading</h2>
<h2 data-onparse="update-2">My Heading</h2>
<div data-onparse="run-oQuickReply.swap()">
This div hasn't yet loaded and nothing will happen.
</div>
First Attempt
第一次尝试
I can build on @JohnWilliams
' <img src>
hack(on this page, from 2017) - which is, so far, the best approach I have come across.
我可以建立在@JohnWilliams
' <img src>
hack(在这个页面上,从 2017 年开始)——到目前为止,这是我遇到的最好的方法。
The example below:
下面的例子:
- Fires the
onerror
EventListener
when the rendering engine parses<img src />
- Executes the
Callback
andremoves the<img src />
from the document
onerror
EventListener
当渲染引擎解析时触发<img src />
- 执行
Callback
和<img src />
从文档中删除
Working Example:
工作示例:
let myHeadingLoadEventTrigger = document.getElementById('my-heading-load-event-trigger');
const updateHeading = (e) => {
let myHeading = e.target.previousElementSibling;
if (true) { // <= CONDITION HERE
myHeading.textContent = 'My Updated Heading';
}
// Modern alternative to document.body.removeChild(e.target);
e.target.remove();
}
myHeadingLoadEventTrigger.addEventListener('error', updateHeading, false);
<h2>My Heading</h2>
<img id="my-heading-load-event-trigger" src />
回答by dota2pro
use an iframe and hide it iframe works like a body tag
使用 iframe 并将其隐藏 iframe 的工作方式类似于 body 标签
<!DOCTYPE html>
<html>
<body>
<iframe style="display:none" onload="myFunction()" src="http://www.w3schools.com"></iframe>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Iframe is loaded.";
}
</script>
</body>
</html>
回答by Floyd Kosch
I needed to have some initialization code run after a chunk of html (template instance) was inserted, and of course I didn't have access to the code that manipulates the template and modifies the DOM. The same idea holds for any partial modification of the DOM by insertion of an html element, usually a <div>
.
我需要在插入一段 html(模板实例)后运行一些初始化代码,当然我无法访问操作模板和修改 DOM 的代码。对于通过插入 html 元素(通常是<div>
.
Some time ago, I did a hack with the onload event of a nearly invisible <img>
contained in a <div>
, but discovered that a scoped, empty style will also do:
前段时间,我对<img>
包含在 a中的几乎不可见的 onload 事件做了一个 hack <div>
,但发现一个有作用域的空样式也可以:
<div .... >
<style scoped="scoped" onload="dosomethingto(this.parentElement);" > </style>
.....
</div>
Update(Jul 15 2017) -
The <style>
onload is not supported in last version of IE. Edge does support it, but some users see this as a different browser and stick with IE. The <img>
element seems to work better across all browsers.
更新(2017 年 7 月 15 日) -<style>
最新版本的 IE 不支持 onload。Edge 确实支持它,但一些用户将其视为不同的浏览器并坚持使用 IE。该<img>
元素似乎在所有浏览器中都能更好地工作。
<div...>
<img onLoad="dosomthing(this.parentElement);" src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" />
...
</div>
To minimize the visual impact and resource usage of the image, use an inline src that keeps it small and transparent.
为了最大限度地减少图像的视觉影响和资源使用,请使用内联 src 使其保持小而透明。
One comment I feel I need to make about using a <script>
is how much harder it is to determine which <div>
the script is near, especially in templating where you can't have an identical id in each instance that the template generates. I thought the answer might be document.currentScript, but this is not universally supported. A <script>
element cannot determine its own DOM location reliably; a reference to 'this' points to the main window, and is of no help.
我觉得我需要对使用 a 发表的一个评论<script>
是确定哪个<div>
脚本靠近的难度有多大,尤其是在模板生成的每个实例中不能具有相同 id 的模板中。我认为答案可能是 document.currentScript,但这并不是普遍支持的。一个<script>
元素不能可靠地确定它自己的 DOM 位置;对“this”的引用指向主窗口,没有帮助。
I believe it is necessary to settle for using an <img>
element, despite being goofy. This might be a hole in the DOM/javascript framework that could use plugging.
我认为有必要满足于使用<img>
元素,尽管它很愚蠢。这可能是 DOM/javascript 框架中可以使用插入的漏洞。