首页 > 解决方案 > 我需要在 classList 模板字符串 javascript 中增加一个数字

问题描述

你好朋友们,我遇到了一个困难,我在我的二十一点游戏中有点陷入困境我创建图像(卡片)并且值来自对象列表中的 .PNG 名称。我想要做的是能够在这些图像上创建一个类,以便能够在其他函数中使用 classList.contain() 方法。它似乎有效,但每次我调用该函数时数字都不会增加。所有的卡都有相同的类。

功能显示卡(活动播放器,卡){

if (activePlayer.score <= 20){
    
    let cardImage = document.createElement("img")
    function incrementNumber(number){
        number = number++
        return number
    }
    //increment the number of the class
    cardImage.classList.add(`images${incrementNumber()}`)
    cardImage.src = `images/${card}.png`
    document.querySelector(activePlayer["div"]).appendChild(cardImage)
    hitSound.play() 
} 

我知道我很可能忘记了一件简单的事情,但我不能把我的手指放在它上面。我在 ${incrementNumber(1)} 中添加了一个数字,仍然为所有图像提供相同的图像类。谢谢你的帮助!

标签: javascripthtmlfunctionincrementtemplate-strings

解决方案


将一个全局变量添加到名为 number 的作用域并将其设置为 1。然后替换number = number++number++.


推荐阅读