5

我正在循环一个数组并修改数组的内容,但我没有得到我期望的结果。我错过了什么或做错了什么?

我有两组 div(一组是攻击者,另一组是敌人),每组包含三个元素。我试图通过在它周围制作边框来从每一侧选择一个元素。现在我想将课程从攻击者切换到敌人,反之亦然。但是当我使用 for 循环时,它会以某种方式忽略一些元素并且只更改一两个 div 类。这是我的代码:

HTML:

<div id="army1">
    <div class="attacker">
        <img src="img/Man/Archer.jpg" />
        <div class="hp"></div>
    </div>
    <br><div class="attacker">
        <img src="img/Man/Knight.jpg" />
        <div class="hp"></div>
    </div>
    <br><div class="attacker">
        <img src="img/Man/Soldier.jpg" />
        <div class="hp"></div>
    </div>
    <br>            
</div>

<div id="army2">
    <div class="enemy">
        <img src="img/Orcs/Crossbowman.jpg" />
        <div class="hp"></div>
    </div>
    <br><div class="enemy">
        <img src="img/Orcs/Mine.jpg" />
        <div class="hp"></div>
    </div>
    <br><div class="enemy">
        <img src="img/Orcs/Pikeman.jpg" />
        <div class="hp"></div>
    </div>
    <br>            
</div>

还有我的javascript代码:

var attacker = document.getElementsByClassName('attacker');
var enemy = document.getElementsByClassName('enemy');


var button = document.getElementById("fight");

// var class1 = document.getElementsByClassName("first")[0].getAttribute("class");
// class1 = class1.split(" ");

//choose attacker
for (var i = 0; i < attacker.length; i++) {
    attacker[i].onclick = function () {
        //select only one attacker and set its id to attackerid
        if (this.getAttribute('class') != 'attacker first') {
            resetAttackerClasses();
            this.setAttribute('class', 'attacker first');
        } else {
            resetAttackerClasses();
        }

    };
}

//choose enemy
for (var i = 0; i < enemy.length; i++) {
    enemy[i].onclick = function () {
        //select only one attacker and set its id to enemyid
        if (this.getAttribute('class') != 'enemy second') {
            resetEnemyClasses();
            this.setAttribute('class', 'enemy second');
        } else {
            resetEnemyClasses();
        }
    };
}

//fight
button.onclick = function() {
    //take off enemy health
    document.getElementsByClassName('enemy second')[0].children[1].style.width = '50px';

    resetAttackerClasses();
    resetEnemyClasses();

     for (var i = 0; i < attacker.length; i++) {
            attacker[i].setAttribute('class', 'enemy');
            enemy[i].setAttribute('class', 'attacker');
    };
};


function resetAttackerClasses() {
    for (var i = 0; i < attacker.length; i++) {
        attacker[i].setAttribute('class', 'attacker');
    };
}
function resetEnemyClasses() {
    for (var i = 0; i < attacker.length; i++) {
        enemy[i].setAttribute('class', 'enemy');
    };
}
4

1 回答 1

8

这是因为您要删除用于获取元素的类,这意味着该元素将自动从活动的 NodeList 中删除(因为它不再与查询匹配)

发生这种情况时,NodeList 被重新索引,因此下一个元素成为当前元素,您最终会用 next 跳过它i++

要修复它,请改为反向迭代。

如果您不想反向,则每次从列表中删除元素时都会减少索引。

于 2013-03-04T18:10:51.813 回答