此测验中的用户可以选择名称:
<p>Wie is jouw allergrootste vijand</p>
<input type="radio" name="vijand" value="Loki" class="vijand"> Loki
<input type="radio" name="vijand" value="Joker" class="vijand"> Joker
<input type="radio" name="vijand" value="Two Face" class="vijand"> Two Face
<input type="radio" name="vijand" value="Red Skull" class="vijand"> Red Skull
<input type="radio" name="vijand" value="Thanos" class="vijand"> Thanos
<input type="radio" name="vijand" value="Killmonger" class="vijand"> Killmonger
<input type="radio" name="vijand" value="Black Adam" class="vijand"> Black Adam
<input type="radio" name="vijand" value="Hela" class="vijand"> Hela
我想将它与数组中的名称进行比较。我的想法是使用索引号来比较这个,所以我尝试使用.indexOf()
,但他没有用。
function vijand(){
var vijanden = ['Loki', 'Joker', 'Two Face', 'Red Skull', 'Thanos', 'Killmonger', 'Black Adam', 'Hela'];
var keuze = document.getElementsByClassName('vijand').value;
var vijandNummer;
//De eerste 4 uit de array
if ( keuze === vijanden.indexOf(0,1,2,3)) {
vijandNummer = 1;
}
else if (keuze === vijanden.indexOf(4,5,6,7) ) {
vijandNummer = 0;
}
return vijandNummer;
}
我做错了什么?
答案 0 :(得分:0)
function vijand(){
var vijanden = ['Loki', 'Joker', 'Two Face', 'Red Skull', 'Thanos', 'Killmonger', 'Black Adam', 'Hela'];
var vijandNummer;
var vijandenValue = document.querySelector('input[name=vijand][checked]').value;
if(['Loki', 'Joker', 'Two Face', 'Red Skull'].indexOf(vijandValue) !== -1) {
vijandNummer = 1
}
if(['Thanos', 'Killmonger', 'Black Adam', 'Hela'].indexOf(vijandValue) !== -1) {
vijandNummer = 0
}
return vijandNummer;
}
答案 1 :(得分:0)
您以错误的方式使用<p>
。你想要:
indexOf
然后:
var index = vijanden.indexOf(keuze); // for keuze = 'Hela', index = 7
假设您的代码,如果选择前四位英雄中的任何一位,则vijandNummer = index < 4 ? 1 : 0;
必须为1,否则为0。