首页 > 解决方案 > 确定是否单击了具有 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)

标签: javascripthtml

解决方案


方法 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


推荐阅读