gpt4 book ai didi

javascript - 图像损坏,但它作为新选项卡加载

转载 作者:行者123 更新时间:2023-12-01 03:09:47 25 4
gpt4 key购买 nike

我有以下小脚本,似乎可以工作,但其中两个图像似乎已损坏。当我右键单击并加载为新选项卡时,它们会加载:

var target = document.getElementById('target');
var counter = 0;
var myPictures = [
'https://media.giphy.com/media/3ohhwJax6g4Y8BK30k/giphy.gif',
'https://media.giphy.com/media/3o7aD5tv1ogNBtDhDi/giphy.gif',
'https://media.giphy.com/media/1nkUav308CBws/giphy.gif'
];

function nextPic() {
counter += 1;
if (counter > myPictures.length -1) {
counter = 0;
}
target.src = myPictures[counter];
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<img id="target" src="https://media.giphy.com/media/1nkUav308CBws/giphy.gif" width="107" height="98" />
<input type="button" onclick="nextPic()" value="change image" />





</body>
</html>

最佳答案

只需将此行移到您的 nextPic() 中即可函数,这样你就不会试图捕获 div在它被加载到 DOM 之前。

function nextPic() {
var target = document.getElementById('target');
...

有时 <script defer> 会自动等待 DOM 加载,有时不会。这是 JavaScript。就是这样。

defer

This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded. This attribute must not be used if the src attribute is absent (i.e. for inline scripts), in this case it would have no effect. To achieve a similar effect for dynamically inserted scripts use async=false instead.

这是一个很好的backstory on script loading .

关于javascript - 图像损坏,但它作为新选项卡加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45926628/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com