簡體   English   中英

在for循環中使用if語句

[英]Using an if statement inside of a for loop

我有一個帶有兩組單選按鈕的表單。 我試圖這樣做,以便當檢查某個值時, <p>元素(帶有ID描述)將使用相應的數據進行更新。

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

演示

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.您沒有在聽單選按鈕更改事件。

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

演示

准備好文檔上單選按鈕的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);
        }
     }
});

看看如何在變更事件中使用廣播? 有關如何為單選按鈕添加事件的詳細信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM