js中怎样设置动态tr的属性

JavaScript011

js中怎样设置动态tr的属性,第1张

两个insert方法返回的就是被插入的对象,直接操作这两个对象就行了。

var tr = table.insertRow()var td = tr.insertCell()tr.setAttribute('align','center') '不用setAttribute而直接使用属性也可以.tr.setAttribute('bgcolor','#FF0000')

td.width=100  直接对属性赋值的作法。

要在tr元素的父元素中才能增加行,不能在tr本身去增加行。而tbody就是tr的父元素。如果是增加td,就要用tr,因为tr是td的父元素。

<script>// Last updated 2006-02-21 function addRowToTable() { var tbl = document.getElementById('tblSample')var lastRow = tbl.rows.length。

// if there's no header row in the table, then iteration = lastRow + 1

var iteration = lastRow。

var row = tbl.insertRow(lastRow)// left cell var cellLeft = row.insertCell(0)var textNode = document.createTextNode(iteration)cellLeft.appendChild(textNode)

// right cell var cellRight = row.insertCell。

var el = document.createElement('input')el.type = 'text'el.name = 'txtRow' + iterationel.id = 'txtRow' + iterationel.size = 40。

el.onkeypress = keyPressTestcellRight.appendChild(el)。

 function onAddTR(trIndex)

        {

            var tb = document.getElementById("tb1")

            var newTr = tb.insertRow(trIndex)//添加新行,trIndex就是要添加的位置

            var newTd1 = newTr.insertCell()

            newTd1.innerHTML = "这是新行,位置:" + trIndex

            var newTd2 = newTr.insertCell()

            newTd2.innerHTML = "这是新行,位置:" + trIndex

        }

请参考采纳,谢谢!