javascript - 确定是否单击了具有 id 的元素
问题描述
如果单击了特定元素,我正在尝试使用事件侦听器来触发函数。下面你会看到有 3 个元素共享“gameselection”类,每个元素都有一个唯一的 id。
到目前为止,如果我查找已单击的特定类,我已经设法让事件侦听器触发。但我需要修改功能,以便它查找具有类和 id 组合的元素。
这是元素的 HTML:
<div class="gameselections">
<div class="gameselection" id="rockdiv">
<p class="gameselectiontext" id="rockselection">Rock</p>
<img class="selection" src="images/rock.png">
</div>
<div class="gameselection" id="paperdiv">
<p class="gameselectiontext" id="paperselection">Paper</p>
<img class="selection" src="images/paper.png">
</div>
<div class="gameselection" id="scissorsdiv">
<p class="gameselectiontext" id="scissorsselection">Scissors</p>
<img class="selection" src="images/scissors.png">
</div>
</div>
这是适用于指定类的 JS:
document.addEventListener("click", gameSelectionListener);
function gameSelectionListener(event) {
let element = event.target;
console.log(event.target);
let rock = "rock";
if (element.classList.contains("gameselection")) {
playRound(rock);
console.log("submitted rock")
}
}
我知道我需要修改 JS 以包含两个标准;但是,我不确定那是什么样子。这是我认为可行的方法:
// Event listener for click
document.addEventListener("click", gameSelectionListener);
// Check and see if the click was on a game selection button (can't apply directly on button as div hidden initially)
function gameSelectionListener(event) {
let element = event.target;
console.log(event.target);
let rock = "rock";
if (element.classList.contains("gameselection") && element.id.contains("rockdiv")) {
playRound(rock);
console.log("submitted rock")
}
}
这是使用上述代码在 JS 控制台中报告的错误:
Uncaught TypeError: element.id.contains is not a function
at HTMLDocument.gameSelectionListener (main.js:54)
解决方案
方法 contains() 将不起作用,因为您尝试在字符串上执行它
您可以通过
event.target.id
你的 if 语句看起来像这样
if (element.classList.contains("gameselection") && element.id == "rockdiv") {
playRound(rock);
console.log("submitted rock")
}
“包含”是一个将在节点上工作的函数
https://developer.mozilla.org/en-US/docs/Web/API/Node/contains
推荐阅读
- ios - 无法在 Google Colab 中复制、剪切或粘贴代码(Google Colab + iOS 错误)
- azure-data-explorer - 条件过滤器的 Kusto 查询帮助
- python - 如何使用 discord.py 定义“get_member”的属性
- r - 当未来的软件包说 mcapply 已知不稳定时,它是什么意思?
- tensorflow - Tensorflow 文本分词器不正确分词
- firebase - Flutter - 从数组中删除重复项
- flutter - 为什么颤振会在 buildSuggestions 中抛出字符串 int 错误,但 buildResults 仍然有效?
- javascript - 使用联系表单 7 的多步骤时自动填充文本字段
- ruby-on-rails - 当字符串包含多个单词时使用 .where 查询不起作用
- ios - 快速改变录制音频的音高和速度