You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用querySelector获取按钮后无法绑定onclick,报Cannot set properties of null错误

问题:点击按钮获取卡牌数据时出现"Cannot set properties of null (setting 'onclick')"错误

我写了一个简单的网页,期望点击按钮后从卡牌API获取单张卡牌数据并打印到控制台,但现在控制台报错"Cannot set properties of null (setting 'onclick')"。我试过移动script标签位置、给JS文件加defer属性,问题还是没解决。

基础HTML代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button class = "hitknop">Hit!</button>
</body>
<script src="index.js" defer></script>

</html>

我的JavaScript代码

const deckinit = "https://deckofcardsapi.com/api/deck/new/shuffle/?deck_count=1";
const hitknoppie = document.querySelector("hitknop");
let deckId;


async function deckophalen(){
    const response = await fetch (deckinit);
    const deckopties = await response.json();
    deckId = deckopties.deck_id;
    console.log(deckId);
}

deckophalen();

hitknoppie.onclick = async function (){
    const kaartlink = `https://deckofcardsapi.com/api/deck/${deckId}/draw/?count=1`;
    const response = await fetch (kaartlink);
    const kaart = await response.json();
    console.log(kaart);
} 

解决方案

报错的核心原因是你用document.querySelector("hitknop")选择元素时,没指定选择器类型。按钮的class是hitknop,但直接写字符串"hitknop",浏览器会把它当作标签名(比如<hitknop>)去查找,自然找不到元素,所以hitknoppie是null,设置onclick时就会报错。

修改方式很简单,在选择器前加上.(类选择器的标识):

// 原代码
const hitknoppie = document.querySelector("hitknop");
// 修改后
const hitknoppie = document.querySelector(".hitknop");

另外,为了更稳妥,建议把事件监听放在DOM完全加载完成后执行(虽然你加了defer,但多一层保障更可靠):

async function init() {
    await deckophalen();
    const hitknoppie = document.querySelector(".hitknop");
    hitknoppie.onclick = async function (){
        const kaartlink = `https://deckofcardsapi.com/api/deck/${deckId}/draw/?count=1`;
        const response = await fetch (kaartlink);
        const kaart = await response.json();
        console.log(kaart);
    } 
}

// 等待DOM加载完成后初始化
document.addEventListener('DOMContentLoaded', init);

这样修改后,就能正常获取按钮元素并绑定点击事件,点击后就能打印卡牌数据了。


内容的提问来源于stack exchange,提问作者DashG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 08:40:47