繁体   English   中英

这是引用整个 window 而不是 forEach 循环中的元素

[英]this is referencing the whole window rather than the element in forEach loop

我是 javascript 的新手,并试图通过构建井字游戏来练习我所知道的。

我在 HTML 中创建了一个网格,并试图通过添加 class 名称来将单击的块更改为 X 或 O 来记录玩家的移动。 我还保存了单击块的 position,最后使用winCheck function 检查最后一步是否导致获胜。

以下是引发错误的代码部分:

    const square = document.querySelectorAll('.square')
    // playing : x starts
    let player = 'x'

    square.forEach(block=>{
        block.addEventListener('click', play(player))
    })

    function play(player) {
        if(!search(this.id,occupied)){
            occupied.push(this.id)
            if(player==='x'){
                this.classList.add('x')
                player = 'o'
                x.push(this.id)
            }else if(player==='o'){
                this.classList.add('o')
                player = 'x'
                o.push(this.id)
            }
            winCheck()
        }
    }

引发的错误:

TypeError: this.classList is undefined

当我在播放function 中执行console.log(this)时,我看到它正在引用完整的窗口(文档或 DOM 或我不知道的正确单词,因为我是前端开发的新手

如果问题缺乏细节,我很抱歉,很难就您不知道的主题提出问题

我要做的第一件事就是向文档添加一个事件侦听器,然后使用事件本身。 当一个人可以做到这一点时,将事件侦听器附加到每个方块是没有意义的。

document.addEventListener('click', (event) => {
    // then you want to make sure that the target of the event is one of your squares
    if (event.target.classList.contains('square')) {
        //you want to handle the event here, so to prevent further bubbling
        event.stopPropagation();
        //then start manipulating the appearance of your square
    }
});

Javascript 中的this关键字在开发的早期阶段会变得相当混乱。 在您对基础知识感到满意并准备好继续进行更复杂的事情之前,我会避免使用它。

你编写了 Vanilla JS 的代码,但是你混合了 jQuery 和 Vanilla JS 的概念。

你的 function play()是事件 function,实际上传入的参数player就是event本身。

所以你应该:

  • 将参数player重命名为event
  • player元素应该是event.currentTarget
  • this原因应该自己设置为player (如果你想使用它)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM