javascript - 单击元素时不会调用单击事件监听器

标签 javascript html

我正在尝试向我的类添加一个 onclick 监听器。我在里面添加了 alert() 方法,但似乎 onclick 从未执行过。我也尝试过使用事件监听器,这给了我同样的问题。

我的代码如下,如何循环遍历我的类并附加事件监听器?

/* Easier function to use than rewriting document.get... */
function getById(id) {
    return document.getElementById(id)
}

function getByClass(c) {
    return document.getElementsByClassName(c)
}

/* Random number calculation */
function random(xOrY) {
    return Math.floor(Math.random() * (+xOrY - +1)) + 1
}

/* Create a grid */
function createGrid(isHiding) {
    var grid = document.createElement("div")
    grid.className = isHiding ? "hiding" : "grid"
    return grid
}

/* Set configurations we will use */
var settings = {
    hiding: 4,
    x: 6,
    y: 6,
    maxAttempts: 6 * 6,
    container: 'grid-container'
}

/* Set up the game */
var game = {
    settings: settings,
    attempts: 0,
    numberFound: 0,
    hidingGrids: []
}

/* Generate the hiding grids */
for (i = 1; i <= game.settings.hiding; i++) {
    game.hidingGrids.push({
        x: random(game.settings.x),
        y: random(game.settings.y)
    })
}

/* Generate the grids */
for (y = 1; y <= game.settings.y; y++) {
    for (x = 1; x <= game.settings.x; x++) {
        var gridHasHid = false
        game.hidingGrids.forEach(function(grid) {
            if (y == grid.y && x == grid.x) {
                gridHasHid = true
                /* Create a hidden grid */
                getById(game.settings.container).appendChild(createGrid(true))
            }
        })
        if (!gridHasHid) {
            /**
             *If it gets here, the grid wasn't a hidden grid
             * thus we need to add a standard grid.
             */
            getById(game.settings.container).appendChild(createGrid(false))
        }
    }
    /* Append a break line to start the next row */
    var br = document.createElement("br")
    getById(game.settings.container).appendChild(br)
}

/* Lets set listen handlers on the incorrect and correct grids */
for (el in getByClass("grid")) {
    el.onclick = function() {
        /* We need to go through all our checks to ensure the game hasn't ended */
        if (game.attempts == game.settings.maxAttempts || game.numberFound == game.settings.hiding) {
            alert("The game is already over.")
            return
        }
        /* Check that the tile hasn't already been clicked using our colour factor */
        if (this.style.background == "red") return
        /* If it got here, all checks passed. Lets update the colour and send an message */
        this.style.background = "red"
        alert("Incorrect, you have " + ++game.attempts + " attempts left.")
    }
}

for (el in getByClass("hiding")) {
    el.onclick = function() {
        /* We need to go through all our checks to ensure the game hasn't ended */
        if (game.attempts == game.settings.maxAttempts || game.numberFound == game.settings.hiding) {
            alert("The game is already over.")
            return
        }
        /* Check that the tile hasn't already been clicked using our colour factor */
        if (this.style.background == "blue") return
        /* If it got here, all checks passed. Lets update the colour and send an message */
        this.style.background = "blue"
        alert("Correct, you have " + ++game.attempts + " attempts left.")
    }
}
#grid-container {
  display: inline-block;
  width: 100%;
}

.grid {
  display: inline-block;
  background-color: #000;
  padding: 5%;
  margin: 2%;
}

.hiding {
  background-color: #000;
  display: inline-block;
  padding: 5%;
  margin: 2%;
}

/* Uncomment below to see where they're hiding (DEBUG) */

.hiding {
  background-color: blue;
}
<div id="grid-container"></div>

最佳答案

您的代码中有一些错误。例如。在此 for 循环中 for (el in getByClass("hiding"))el 只会为您提供键值,而不是整个元素。

你需要像这样获取元素 getByClass("hiding")[el].onclick = function() {

我添加了一些代码。试试这个

/* Easier function to use than rewriting document.get... */
function getById(id) {
    return document.getElementById(id)
}

function getByClass(c) {
    return document.getElementsByClassName(c)
}

/* Random number calculation */
function random(xOrY) {
    return Math.floor(Math.random() * (+xOrY - +1)) + 1
}

/* Create a grid */
function createGrid(isHiding) {
    var grid = document.createElement("div")
    grid.className = isHiding ? "hiding" : "grid"
    return grid
}

/* Set configurations we will use */
var settings = {
    hiding: 4,
    x: 6,
    y: 6,
    maxAttempts: 6 * 6,
    container: 'grid-container'
}

/* Set up the game */
var game = {
    settings: settings,
    attempts: 0,
    numberFound: 0,
    hidingGrids: []
}

/* Generate the hiding grids */
for (i = 1; i <= game.settings.hiding; i++) {
    game.hidingGrids.push({
        x: random(game.settings.x),
        y: random(game.settings.y)
    })
}

/* Generate the grids */
for (y = 1; y <= game.settings.y; y++) {
    for (x = 1; x <= game.settings.x; x++) {
        var gridHasHid = false
        game.hidingGrids.forEach(function(grid) {
            if (y == grid.y && x == grid.x) {
                gridHasHid = true
                /* Create a hidden grid */
                getById(game.settings.container).appendChild(createGrid(true))
            }
        })
        if (!gridHasHid) {
            /**
             *If it gets here, the grid wasn't a hidden grid
             * thus we need to add a standard grid.
             */
            getById(game.settings.container).appendChild(createGrid(false))
        }
    }
    /* Append a break line to start the next row */
    var br = document.createElement("br")
    getById(game.settings.container).appendChild(br)
}

/* Lets set listen handlers on the incorrect and correct grids */
for (el in getByClass("grid")) {
    getByClass("grid")[el].onclick = function() {
        /* We need to go through all our checks to ensure the game hasn't ended */
        if (game.attempts == game.settings.maxAttempts || game.numberFound == game.settings.hiding) {
            alert("The game is already over.")
            return
        }
        /* Check that the tile hasn't already been clicked using our colour factor */
        if (this.style.background == "red") return
        /* If it got here, all checks passed. Lets update the colour and send an message */
        this.style.background = "red"
        alert("Incorrect, you have " + ++game.attempts + " attempts left.")
    }
}

for (el in getByClass("hiding")) {
    getByClass("hiding")[el].onclick = function() {
        /* We need to go through all our checks to ensure the game hasn't ended */
        if (game.attempts == game.settings.maxAttempts || game.numberFound == game.settings.hiding) {
            alert("The game is already over.")
            return
        }
        /* Check that the tile hasn't already been clicked using our colour factor */
        if (this.style.background == "blue") return
        /* If it got here, all checks passed. Lets update the colour and send an message */
        this.style.background = "blue"
        alert("Correct, you have " + ++game.attempts + " attempts left.")
    }
}
#grid-container {
  display: inline-block;
  width: 100%;
}

.grid {
  display: inline-block;
  background-color: #000;
  padding: 5%;
  margin: 2%;
}

.hiding {
  background-color: #000;
  display: inline-block;
  padding: 5%;
  margin: 2%;
}

/* Uncomment below to see where they're hiding (DEBUG) */

.hiding {
  background-color: blue;
}
<div id="grid-container"></div>

关于javascript - 单击元素时不会调用单击事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56058931/

相关文章:

javascript - Angularjs 图表没有调整大小

javascript - 自定义 Stripe 按钮

javascript - 如何访问 javascript 中的 laravel .env 变量?

java - 用户进入特定网页后如何禁用刷新按钮?

css - div 始终位于页面顶部,随机图像自动适合该 div

javascript - 根据多个单选按钮选择显示或隐藏元素

html - div 中的元素过早折叠

javascript - AngularJs:如何在两个范围之间进行通信

javascript - iPhone 的 safari 上的视频标签不会触发触摸事件

javascript - 循环中的 jQuery click()