如何将值从下拉列表推送到数组并将数组添加到表中?

时间:2015-04-22 13:27:56

标签: javascript html arrays

这是JavaScript。该选择的idcounties

该表格将被插入名为“div”的up_bottom

var leagueArray = [];
function addTeams() {
  var county=document.getElementById("counties");
  var val = county.options[county.selectedIndex].value;
  leagueArray.push(val);
  function display() {
    var table = document.createElement("table");
    for (var i=0; i<leagueArray.length; i++) {
      var row = table.insertRow();
      for (var j=0; j<leagueArray[i].length; j++) {
        var cell = row.insertCell();
        cell.appendChild(document.createTextNode(leagueArray[i]));
      }
    }
    var tableDiv = document.getElementById("up_bottom");
    tableDiv.appendChild(table);
  }
  display();
}

2 个答案:

答案 0 :(得分:0)

试试这个,

function addTeams(){
    var leagueArray = [];
    var county=document.getElementById("counties");
    for (i = 0; i < county.options.length; i++) {
       leagueArray[i] = county.options[i].value;
    }
    display(leagueArray);
}

function display(leagueArray) {
    var table = document.createElement("table");
    for (var i=0; i<leagueArray.length; i++) {
        var row = table.insertRow();
        for (var j=0; j<leagueArray[i].length; j++) {
            var cell = row.insertCell();
            cell.appendChild(document.createTextNode(leagueArray[i]));
        }
    }
    var tableDiv = document.getElementById("up_bottom");
    tableDiv.appendChild(table);
}

addTeams();

答案 1 :(得分:0)

请执行以下步骤

  1. 从下拉列表中获取选定的值
  2. 将所选值放入数组
  3. 创建一个tr元素的字符串,并将其附加到第一个tr元素
  4. 之前的表中