首页 > 解决方案 > 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.

标签: javascriptbutton

解决方案


添加 if 语句来检查您的 downloadButton 是否存在将解决您的问题。

    <script>
    var downloadButton = document.getElementById("download2"); 
    if( downloadButton ){
      //rest of your code goes inside.
    }
    
</script>

推荐阅读