尝试通过类名获取多个<span>元素并将其值更改为true或false

时间:2018-09-13 02:33:14

标签: javascript html boolean element

我几乎已经尝试了所有可能的方法,对此我是超新的。

我试图使用类名来获取元素,然后试图将其值更改为true,以便我可以运行使用.push和if / else语句构建的新函数。基于范围值的数组(我将在底部发布该函数)

任何人都可以提供的帮助将是很棒的,我过去三个晚上一直在这里,但我一直受困,我必须在明天之前解决此问题。.:(

预先感谢十亿!

JavaScript

// Function Declaration to check the user's character choice.
function userChoiceCheck(uChoice, low) {
    for (var j = 0; j < low.length; j++) {
        if (uChoice == low[j]) {
            var element = document.getElementsByClassName(low[j]);
            element.setAttribute = "true";
             console.log(element);
             console.log("The value of " + low[j] + " should now be true!");
        } else {
            document.getElementsByClassName(low[j].class).value = "false";
            console.log("The value of " + low[j] + " should now be false!");
        }
    }
}

HTML

<div class="text-center pt-5">
    <h1 id="wordGuessArea">
    <span class="m" value="false">__ </span>
    <span class="o" value="false">__ </span>
    <span class="o" value="false">__ </span>
    <span class="s" value="false">__ </span>
    <span class="e" value="false">__ </span>
    </h1>
</div>

上述功能

// Function Declaration to merge censoredWord Array and upper Array into a 
new array called displayArr. Depending on the boolean value of the span that 
contains the character.
function mergeArr(low, up, wSplit, cWord) {
    for (var m = 0; m < wSplit.length; m++) {
        var targetCharSpan = document.getElementsByClassName(low[m]);
        var charSpanVal = targetCharSpan.value;
        if (charSpanVal == true) {
            displayArr.push(up[m]);
        } else if (charSpanVal == false) {
            displayArr.push(cWord[m]);
        }
    }
}

2 个答案:

答案 0 :(得分:1)

我认为您在按类获取所有元素方面遇到困难,

如果是这样,则需要循环

getElementsByClassName返回一个数组 HTMCollection,而不是使用element.setAttribute,而是应该遍历element变量中的每个元素

赞:

for(let i=0;i<element.length;i++)
{
   element[i].setAttribute = "true";
}

答案 1 :(得分:0)

您可以使用jQuery通过这种方式解决问题

<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>

<body>

<div class="text-center pt-5">
    <h1 id="wordGuessArea">
    <span class="m" value="false">__ </span>
    <span class="o" value="false">__ </span>
    <span class="o" value="false">__ </span>
    <span class="s" value="false">__ </span>
    <span class="e" value="false">__ </span>
    </h1>
</div>

<script>

for(var i=0;i<$('#wordGuessArea span').length;i++){
   //Applying for all span elements inside wordGuessArea id

   $('#wordGuessArea span').html('Bla'); 

}
</script>

</body>