jquery - 未捕获的类型错误:无法设置属性“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。
解决方案
您可以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);
});
推荐阅读
- macos - 在 Mac 上使用以太网电缆将 VNC 插入 Raspberry Pi 3B+ 当 Mac 上的 wifi 打开时,OSX 失去连接
- java - 有人可以为我解释以下代码的含义是什么
- google-apps-script - 加速电子表格的脚本(GAS - Google App Script & Google Sheets)
- python - 如何从列表中返回一个字典,其中键是列表中的项目,值是 python 中该列表中出现的次数?
- html - 如何在 div 的边框中添加文本?
- python - 如何从 pandas.io.common 导入名称?
- ffmpeg - 无法使用 quicktime 打开 ffmpeg 输出,pix_fmt 标志无法修复它
- javascript - 在 Javascript 中定义函数的符号差异
- c# - DataGridComboBoxColumn 透明 ComboBoxItems
- spring-boot - Gradle spring-boot 错误 - java.lang.ClassNotFoundException: org.springframework.boot.SpringApplication