2016-04-27 181 views
0

我有一個包含兩組單選按鈕的窗體。 我試圖做到這一點,當某個值被選中時,一個<p>元素(帶有Id描述符)將會用相應的數據進行更新。在for循環中使用if語句

這就是我所擁有的,它現在沒有更新元素。

DEMO

function classStats() { 
    classes = ['archer', 'mage', 'warrior']; 
    classStats = ['HP: 20 Strength: 3 Intellect: 1 Speed: 5 Magic Defense: 1 Defense: 3', 'HP: 15 Strength: 1 Intellect: 6 Speed: 2 Magic Defense: 2 Defense: 1', 'HP: 30 Strength: 2 Intellect: 1 Speed: 1 Magic Defense: 3 Defense: 5']; 
    classAdd = ['The archer also has a special passive for armor penetration.', 'The mage has a special passive for increased gold gain', 'The warrior has a special passive for percent damage mitigation.']; 
    for (i = 0; i < 3; i++) { 
    c = classes[i]; 
    e = classStats[i]; 
    f = classAdd[i]; 
    if ($('input[name=class]:checked').val() === c) { 
     $('#descript').text(e + ' ' + f); 
    } 
    } 
} 
classStats(); 
+1

'I> 4'始終爲false。 –

+1

你的問題是什麼?另外我> 4? – brk

+0

更正了它在我的演示https://jsfiddle.net/sq5hntpv/2/應該是我<3 – Shniper

回答

-1

添加onchange事件的單選按鈕上的文件準備好。並且在事件被觸發時調用你的代碼。

$('input[name=class]').change(function() { 
    classes = ['archer', 'mage', 'warrior']; 
    classStats = ['HP: 20 Strength: 3 Intellect: 1 Speed: 5 Magic Defense: 1 Defense: 3', 'HP: 15 Strength: 1 Intellect: 6 Speed: 2 Magic Defense: 2 Defense: 1', 'HP: 30 Strength: 2 Intellect: 1 Speed: 1 Magic Defense: 3 Defense: 5']; 
    classAdd = ['The archer also has a special passive for armor penetration.', 'The mage has a special passive for increased gold gain', 'The warrior has a special passive for percent damage mitigation.']; 
    for (i = 0; i < 3; i++) { 
     c = classes[i]; 
     e = classStats[i]; 
     f = classAdd[i]; 
     if ($('input[name=class]:checked').val() === c) { 
      $('#descript').text(e + ' ' + f); 
     } 
    } 
}); 

查看How to use radio on change event?瞭解有關如何爲單選按鈕添加事件的詳細信息。

1

您的代碼存在多個問題: -

1.您沒有收聽單選按鈕更改事件。

2.不需要循環。

下面是你的代碼的修改和優化版本。

var classes = ['archer', 'mage', 'warrior']; 
var classStats = ['HP: 20 Strength: 3 Intellect: 1 Speed: 5 Magic Defense: 1 Defense: 3', 'HP: 15 Strength: 1 Intellect: 6 Speed: 2 Magic Defense: 2 Defense: 1', 'HP: 30 Strength: 2 Intellect: 1 Speed: 1 Magic Defense: 3 Defense: 5']; 
var classAdd = ['The archer also has a special passive for armor penetration.', 'The mage has a special passive for increased gold gain', 'The warrior has a special passive for percent damage mitigation.']; 
var c,e,f; 

$('input[name=class]').change(function(){ 
    c = classes.indexOf($(this).val()); 
    e = classStats[c]; 
    f = classAdd[c]; 
    $('#descript').text(e + ' ' + f); 
}); 

DEMO