javascript - Uncaught TypeError: downloadButton is null
问题描述
I have added a download button on a few pages that appears after 10 seconds with this code (theme footer):
<script>
var downloadButton = document.getElementById("download2");
var counter = 10;
var newElement = document.createElement("p");
newElement.innerHTML = "10 seconds";
var id;
downloadButton.parentNode.replaceChild(newElement, downloadButton);
id = setInterval(function()
{counter--;
if(counter < 0) {
newElement.parentNode.replaceChild(downloadButton, newElement);
clearInterval(id);
} else {
newElement.innerHTML = " " + counter.toString() + " seconds";
}}, 1000);
</script>
It is working fine. However, on any page that doesn't have a button I get the error "Uncaught TypeError: downloadButton is null". Does that mean the script loads everywhere and on pages without a download button it throws this error? I tried to wrap the script in a ready function with
$( document ).ready(function() {
});
but I couldn't get it to work. Can anyone help me out here? Thank you in advance.
解决方案
添加 if 语句来检查您的 downloadButton 是否存在将解决您的问题。
<script>
var downloadButton = document.getElementById("download2");
if( downloadButton ){
//rest of your code goes inside.
}
</script>
推荐阅读
- python - 扩展从 UI 文件加载的小部件
- python - Python 3 CSV 整数到字节 + \n
- excel - 如果范围单元格包含任何数字或空白单元格,则
- python - 用 Python 计算和打印年龄
- java - 如果生成源没有改变,我如何阻止 Maven 重新生成某些东西?
- selenium-webdriver - 我的 XPath 在对话框上定位输入字段,在脚本中不起作用?
- machine-learning - 通过 k-means 传递数据帧时出错
- r - 如何将指示符列转换为连接列(列名)
- c++ - 防止客户端保留 C++ 类返回的指针
- nginx - Kubernetes 在哪里拉取图像,我如何浏览它们/更改它们的拉取源?