【问题标题】:Uncaught TypeError: Cannot set property 'src' of null but Have set ID未捕获的类型错误:无法设置属性“src”为空,但已设置 ID
【发布时间】:2018-07-06 15:56:38
【问题描述】:

我有这个脚本,它为 img 标签添加一个 ID,然后是一个函数,它用不同颜色的版本更改图像 src,如下所示:

<script type="text/javascript">
jQuery(document).ready(function( $ ) {
$('.custom-logo-link img').each(function(i) {
$(this).attr('id', 'img-logo' + i);
});
});

function setImg(){
var numRand = Math.floor((Math.random() * 4) + 1);
document.getElementById("img-logo0").src = "/wp-content/uploads/2018/04/Logo"+numRand+".jpg";}

setImg();

window.setInterval("setImg()",1000);
</script>

我的问题是我不断收到 Uncaught TypeError: Cannot set property 'src' of null 但我已经设置了它应该查看的 ID。

【问题讨论】:

  • 您能否提供一个有效的 js/html 代码示例?

标签: jquery image src


【解决方案1】:

您可以在准备好的文档中移动setImg(),这样就不会出现ID尚未设置和getElementById失败的问题:

jQuery(document).ready(function( $ ) {
    $('.custom-logo-link img').each(function(i) {
        $(this).attr('id', 'img-logo' + i);
    });

// Move this to the end: });

    function setImg(){
        var numRand = Math.floor((Math.random() * 4) + 1);
        document.getElementById("img-logo0").src = "/wp-content/uploads/2018/04/Logo"+numRand+".jpg";
    }
    setImg();
    window.setInterval(setImg, 1000);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-11
    相关资源
    最近更新 更多