for循环类名称中的“if语句”未定义

时间:2016-12-26 09:55:17

标签: javascript if-statement for-loop classname

每张卡的类名为“card player1card ________”或“card player2card _______”,其中空格是从cardnames数组中分配的随机类名。

我希望代码检查所有卡片,以及那些是player1卡片的人将他们的班级更改为“card player1card”,然后更新班级来自cardnames数组,同样适用于player2card。

所有变量都已预定义。

我收到错误“Uncaught TypeError:无法设置未定义的属性'className'”

var cardsnames = ["recruitbuilder", "allwood", "cabin", "messhall", "mast", "captainsquarters", "schooner", "brig", "frigate", "shipballista", "ram", "crowsnest", "spoondrill", "reinforcements", "recruitgunman", "allgunpowder", "firebarrel", "fireship", "roundshot", "heavyshot", "swivelgun", "chainshot", "mortar", "barrage", "resupply", "smuggler", "blockade", "mutiny", "recruitmerchant", "allgold", "addwood", "addgunpowder", "addgold", "removewood", "removegunpowder", "removegold", "byzantinefire", "slaves", "mercenaries", "ironplating", "coercion", "ascension"];

var w;
var allocatedcard;
var card = document.getElementsByClassName("card");

for (w = 0; w < card.length; w++) {
    if (document.getElementsByClassName("card")[w].className.match('player1card')) {
        this.className = "card player1card";
        var allocatedcard = Math.floor(Math.random() * cardsnames.length);
        this.className += " " + cardsnames[allocatedcard];
        updateimages();             
    } else if (document.getElementsByClassName("card")[w].className.match('player2card')) {
        this.className = "card player2card";
        var allocatedcard = Math.floor(Math.random() * cardsnames.length);
        this.className += " " + cardsnames[allocatedcard];
        updateimages();     
    }
}

1 个答案:

答案 0 :(得分:0)

仅针对上下文,问题中的代码将是另一个函数中的函数。所以我这样做了:

var recruitbuilder = document.getElementsByClassName('recruitbuilder');
var f;
var className = "";
var cardsnames = ["recruitbuilder", "allwood", "cabin", "messhall", "mast", "captainsquarters", "schooner", "brig", "frigate", "shipballista", "ram", "crowsnest", "spoondrill", "reinforcements", "recruitgunman", "allgunpowder", "firebarrel", "fireship", "roundshot", "heavyshot", "swivelgun", "chainshot", "mortar", "barrage", "resupply", "smuggler", "blockade", "mutiny", "recruitmerchant", "allgold", "addwood", "addgunpowder", "addgold", "removewood", "removegunpowder", "removegold", "byzantinefire", "slaves", "mercenaries", "ironplating", "coercion", "ascension"];
var allocatedcard = cardsnames[Math.floor(Math.random() * cardsnames.length)];

for (f = 0; f < recruitbuilder.length; f++) {
    recruitbuilder[f].onclick = function() {
        recruitbuilderfunc(p1);
        displayvaluesp1(p1);
        if (this.classList.contains('player1card') == true ) {
            className = "player1card";
        } else if (this.classList.contains('player2card') == true ) {
            className = "player2card";
        }
      //this.className += " " + cardsnames[allocatedcard];

      this.className = "card " + className + " " + allocatedcard;
      updateimages();
    }
}