簡體   English   中英

如何在JavaScript中檢查數組中僅選中的復選框

[英]How to check for only checked checkboxes in an array in javascript

我正在使用code.org庫。 我正在嘗試僅使用選中的復選框來選擇兩個球隊參加棒球比賽。 目前,我只能選擇1個團隊,但我需要有效地選擇兩個團隊,而不僅僅是前往array的下一個團隊。 我從來沒有在JavaScript看到過這樣的問題。

onEvent("btnStart","click", function() {
    var chkBoxs = ["Yankees","Boston","Astros"];
    var index = 0;
    while (index < chkBoxs.length && !getChecked(chkBoxs[index])) {
      index++;
    }
    setScreen("game");
    console.log("The Teams are: " + chkBoxs[index]+" And "+chkBoxs[index+1]);
});

假設我理解這個問題,您可以使用數組單獨跟蹤選定的團隊:

onEvent("btnStart","click", function() {
    var chkBoxs = ["Yankees","Boston","Astros"];
    var indexes = [];
    for (var i =0; i < chkBoxs.length; i++) {
       if (getChecked(chkBoxs[index]))) {
          indexes.push(index); // store team index
       } 
    }
    setScreen("game");
    console.log("The Teams are: " + chkBoxs[indexes[0]]+" And "+chkBoxs[indexes[1]]);
});

這還假設您始終有兩個團隊。 否則,您將不得不不同地處理最后一行。 如果您需要的只是團隊名稱:

onEvent("btnStart","click", function() {
    var chkBoxs = ["Yankees","Boston","Astros"];
    var teams = [];
    for (var i =0; i < chkBoxs.length; i++) {
       if (getChecked(chkBoxs[index]))) {
          teams.push(chkBoxs[index]); // store team name
       } 
    }
    setScreen("game");
    console.log("The Teams are: " + teams.join(', ') + ".");
});

將所選的放置在新陣列中。

另外,請記住在繼續執行程序之前檢查是否已成功找到兩個。

例:

onEvent("btnStart","click", function() {
    var chkBoxs = ["Yankees","Boston","Astros"];
    var selected = [];
    for (index = 0; selected.length < 2 && index < chkBoxs.length; index++) {
        if (getChecked(chkBoxs[index])) { selected.push(index); }
    }
    setScreen("game");
    if (selected.length == 2) {
        console.log("The Teams are: " + chkBoxs[selected[0]] + " and " + chkBoxs[selected[1]]);
    }
});

暫無
暫無

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

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