首页 > 解决方案 > 未捕获的类型错误:无法设置属性“src”为空,但已设置 ID

问题描述

我有这个脚本,它向 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。

标签: jqueryimagesrc

解决方案


您可以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);
});

推荐阅读