I GET ERROR TypeError:无法读取null

时间:2018-01-09 14:23:25

标签: javascript typeerror addeventlistener

我有以下代码片段,我不确定为什么事件监听器不起作用。它给出了错误:Uncaught TypeError: Cannot read property 'addEventListener' of null

var btn = document.getElementById("button");

var priceshow = document.querySelector("#price");

btn.addEventListener("click", function(){
    var XHR = new XMLHttpRequest();

    XHR.onreadystatechange = function() {
        if (XHR.readyState == 4 && XHR.status == 200) {
            var data = JSON.parse(XHR.responseText);
            var price = data.bpi.GBP.rate;
            priceshow.innerText = price;
        }
    }

    var url = "https://api.coindesk.com/v1/bpi/currentprice.json";
    XHR.open("GET", url);
    XHR.send();
}

1 个答案:

答案 0 :(得分:1)

btn = document.getElementById("button"); btn为null,因为找不到它(带有id按钮的元素)。我认为按钮没有id按钮。