JS'加载'函数在同一时间调用

JS 'onload' function calls infine time

本文关键字:同一时间 调用 加载 JS 函数      更新时间:2024-05-26

如果我们用onload替换onclick事件,那么为什么灯泡会无限长地开关?以下是w3schools的示例,只需将onclick替换为onload并提交代码即可。

示例:-

<!DOCTYPE html>
<html>
<body>
<script>
function changeImage() {
    element = document.getElementById('myimage')
    if (element.src.match("bulbon")) {
        element.src = "pic_bulboff.gif";
    } else {
        element.src = "pic_bulbon.gif";
    }
}
</script>
<img id="myimage" onload="changeImage()"
src="pic_bulboff.gif" width="100" height="180">
<p>Click the light bulb to turn on/off the light</p>
</body>
</html>

每次成功加载图像时,都会触发图像的onload事件。这意味着,如果您更改src,则新图像将加载到<img>"容器"中,并在完成后触发onload(或onerror)。

必须删除事件处理程序。this.onload = null;会做到这一点。(假设你在偶数处理程序中——在这种情况下,你需要做onLoad="changeImage(); this.onload = null;",或者在函数中调整你的代码。

大致而言,

在"页面"加载:

<body onload="...">

在"图像"加载上:

<img onload="..." />

因为它正在暗中加载新的图像

只需添加

element.onload = undefined;

到您的功能