表应该改变行数/列数?

时间:2013-09-17 21:55:05

标签: javascript css html-table

请参阅下面的代码,该表应根据下面所选id选项中选择的输入更改行数,但只读取select id的第一个值,并且行数不会根据选择,你能指出我的代码中的错误吗?

http://jsfiddle.net/uTY6n/14/

HTML:

  <div id="scrollingDiv">
<select id="read">
    <option value="1">1</option>
    <option value="2">2</option></select>

<table id="contentTable" border="1">
    <!-- Fill table programmatically -->
</table>
 </div>

JAVASCRIPT:

  function buildTable()
 {
var myTable =document.getElementById("contentTable");
var j=document.getElementById("read").value;
var rows = [];
var cells = [];

for( var i = 0; i < j; i++ )
{
    rows[i] = myTable.insertRow(i);
    if(i%3==2)rows[i].addClass("everyrow");
    cells[i] = [];

    for( var x = 0; x < 3 ; x++ )
    {
        cells[i][x] =document.createElement((x==0)?"th":"td");
        cells[i][x].innerHTML = (x==0)?"<input>":"<input>";
        rows[rows.length - 1].appendChild(cells[i][x]);
    }
  }

   }
   buildTable();

CSS:

  #scrollingDiv
  {
  border: 1px groove black;
  height: 350px;
  width: 350px;
  background: #ffffff;
  overflow: auto;
  }

  #contentTable
  {
  height: 350px;
  width: 350px;
  }
  .every3rdrow{
  border-bottom:3px solid black;
  }

2 个答案:

答案 0 :(得分:0)

See this demo.

首先,您需要将事件监听器附加到<select>

document.getElemenyById('read').addEventListener('change', buildTable);

然后,每次调用buildTable()时,您需要确保在重建表之前清空该表:

function buildTable() {
    var myTable =document.getElementById("contentTable");
    var j=document.getElementById("read").value;
    var rows = [];
    var cells = [];

    while (myTable.hasChildNodes()) {
        myTable.removeChild(myTable.lastChild);
    }

    ...
}

希望这有帮助!

答案 1 :(得分:0)

function buildTable() {

var myTable =document.getElementById("contentTable");
myTable.innerHTML = "";
var j=document.getElementById("read").value;
var rows = [];
var cells = [];
var myHtml = "";

    for( var i = 0; i < j; i++ ) {
        myHtml += "<tr>";
             for( var x = 0; x < 3 ; x++ ){
                myHtml += "<td></td>"
             }
        myHtml += "</tr>";
    }
myTable.innerHTML = myHtml;
}

这就是一般的想法,也一定要调用你选择的onChange