0

我正在学习如何为 Web 开发编写代码,但遇到了问题。两行几乎相同的代码给了我不同的结果:

for(i=0; i<=lunarSpells.length; i++){
    document.getElementById(lunarSpells[i]).innerHTML =
    Math.ceil(xpLeft/document.getElementById(lunarSpells[i]+"XP").innerHTML);   
}
for(i=0; i<=standardSpells.length; i++){
    document.getElementById(standardSpells[i]).innerHTML =
    Math.ceil(xpLeft/document.getElementById(standardSpells[i]+"XP").innerHTML);    
}

不确定它的重要性,但想法是从数组中取出一个元素,在文档中找到它,然后相应地填写表格。以下是数组:

var lunarSpells = ["cureOther", "NPCContact", "curePlant", "monsterExamine", "bakePie", "cureMe", "TGMoonclan",
                            "TPMoonclan", "TGBarbarian", "superglass", "TPKhazard", "TGKhazard", "dream", "stringJewellery",
                            "statRestorePotShare", "statSpy", "TPBarbarian", "TPWaterbirth", "cureGroup", "TGWaterbirth", "humidify",
                            "hunterKit", "fertileSoil", "plankMake", "TPCatherby", "TGFishingGuild", "TGCatherby", 
                            "boostPotionShare", "TPIcePlateau", "energyTransfer", "healOther", "TGIcePlateau", "vengeanceOther",
                            "vengeance", "healGroup", "spellbookSwap", "magicImbue", "TPFishingGuild"]

var standardSpells = ["confuse", "sapphire", "weaken", "bananas", "curse", "lowAlch", "TPVarrock", "emerald", "TPLumbridge", "TPFalador", "TPHouse",
                                "superheat", "TPCamelot", "ruby", "TPArdougne", "highAlch", "earth", "water", "diamond", "TPWatchtower", 
                                "peaches", "TPTrollheim", "fire", "TPApe", "vulnerability", "air", "dragonstone", "enfeeble", "TOLumbridge", "stun", 
                                "TOFalador", "onyx", "TOCamelot"]

所以我的问题是,为什么 lunarspells 变量有效,而standardspells 变量无效?非常感谢任何帮助,因为我对 HTML 和 JS 还是很陌生。

4

1 回答 1

0

如前所述:

xpLeft/document.getElementById(lunarSpells[i]+"XP").innerHTML

document.getElementById("id_that_doesnt_exist")如果评估为null(as null.anythingis an error.)将失败。

这将停止<script>块中的所有进一步处理,除非您避免错误或换行try/ catch

所以你的第二个循环不会被到达/执行。

于 2013-04-11T19:43:20.403 回答