gpt4 book ai didi

javascript - 将类添加到 HTML 标记 (

) 返回错误

转载 作者:行者123 更新时间:2023-11-28 02:24:10 25 4
gpt4 key购买 nike

我正在尝试向 HTML 标记 ( <p></p> ) 添加一个类,但是当我运行代码时,它返回一个错误:

Uncaught TypeError: Cannot read property 'classList' of null

window.addEventListener('keydown', onKeydown);

const num_ok = [13, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 190];
const del_ = 46;
const back_ = 8;

function getElementByKeyCode(keyCode) {
return document.querySelector(`[data-key = '${keyCode}']`); //tag <p></p>
}

function changeColor(keyCode, opts = {}) {
const element = getElementByKeyCode(keyCode);

if (opts.num || opts.ok) {
element.classList.add('green'); //error when keydown
} else if (opts.del) {
element.classList.add('red'); //error when keydown
} else if (opts.back) {
element.classList.add('yellow'); //error when keydown
}

setTimeout(() => {
deactive(element)
}, 1000);
}

function deactive(element) {
element.className = "num";
}

function onKeydown(event) {
if (num_ok.includes(event.keyCode)) {
changeColor(event, {
num: true,
ok: true
});
} else if (event.keyCode == del_) {
changeColor(event, {
del: true
});
} else if (event.keyCode == back_) {
changeColor(event, {
back: true
});
}
}
.num {
color: #fff;
}
p.red {
color: #e74c3c;
}
p.yellow {
color: ffc300;
}
p.green {
color: #2ecc71;
}
<div class="btns" id="n1">
<p class="center normal num" data-key="49">1</p>
</div>

最佳答案

调用 changeColor() 时传递的是整个事件而不是 event.keyCode。我可以看到您只有 num1 击键所需的元素,但其余数字没有相同的元素。我猜这只是问题的简短版本。

window.addEventListener('keydown', onKeydown);

const num_ok = [13, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 190];
const del_ = 46;
const back_ = 8;

function getElementByKeyCode(keyCode) {
return document.querySelector(`[data-key = '${keyCode}']`); //tag <p></p>
}

function changeColor(keyCode, opts = {}) {
const element = getElementByKeyCode(keyCode);

if (opts.num || opts.ok) {
element.classList.add('green'); //error when keydown
} else if (opts.del) {
element.classList.add('red'); //error when keydown
} else if (opts.back) {
element.classList.add('yellow'); //error when keydown
}

setTimeout(() => {
deactive(element)
}, 1000);
}

function deactive(element) {
element.className = "num";
}

function onKeydown(event) {
if (num_ok.includes(event.keyCode)) {
changeColor(event.keyCode, {
num: true,
ok: true
});
} else if (event.keyCode == del_) {
changeColor(event, {
del: true
});
} else if (event.keyCode == back_) {
changeColor(event, {
back: true
});
}
}
.num {
color: #fff;
}
p.red {
color: #e74c3c;
}
p.yellow {
color: ffc300;
}
p.green {
color: #2ecc71;
}
<div class="btns" id="n1">
<p class="center normal num" data-key="49">1</p>
</div>

关于javascript - 将类添加到 HTML 标记 (<p>) 返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48038484/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com