在for循环中使用if语句

时间:2016-04-27 03:54:48

标签: javascript jquery arrays if-statement for-loop

我有一个带有两组单选按钮的表单。 我试图这样做,以便在检查某个值时,<p>元素(带有Id描述)将使用相应的数据进行更新。

这就是我所拥有的,它现在还没有更新元素。

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();

2 个答案:

答案 0 :(得分:1)

您的代码中存在多个问题: -

1.你不是在听radiobutton改变事件。

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

答案 1 :(得分:-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?,了解有关如何为单选按钮添加事件的详细信息。