根据我在JavaScript中的理解,可以使用element.attribute = newValue
设置任何属性。因此,我尝试使用element.colspan = 2
设置多个表格单元格的colspan,但它不起作用。任何建议表示赞赏。我的代码如下。
table td, table th{ border: 2px solid #0f0f0f; text-align:center; }
.noDisplay{ display:none; }

<html>
<body>
<table>
<tbody>
<tr class = "dateCells" ><td colspan = "1">DATE</td></tr>
<tr><td>Cell One</td><td class = "cells noDisplay">Cell Two</td></tr>
<tr><td>Cell One</td><td class = "cells noDisplay">Cell Two</td></tr>
<tr><td>Cell One</td><td class = "cells noDisplay">Cell Two</td></tr>
<tr><td>Cell One</td><td class = "cells noDisplay">Cell Two</td></tr>
<tr class = "dateCells" ><td colspan = "1">DATE</td></tr>
<tr><td>Cell One</td><td class = "cells noDisplay">Cell Two</td></tr>
<tr><td>Cell One</td><td class = "cells noDisplay">Cell Two</td></tr>
<tr><td>Cell One</td><td class = "cells noDisplay">Cell Two</td></tr>
<tr><td>Cell One</td><td class = "cells noDisplay">Cell Two</td></tr>
</tbody>
</table>
<br>
<div onclick = "clicked()">CLICK<br>HERE</div>
<script>
function clicked(){
var cells = document.getElementsByClassName( 'cells' );
for( var i = 0; i < cells.length; i++ ){
cells[ i ].classList.remove( 'noDisplay' );
}
var dateCells = document.getElementsByClassName( 'dateCells' );
for( var i = 0; i < dateCells.length; i++ ){
dateCells[ i ].colspan = 2;
}
}
</script>
</body>
</html>
&#13;
如上所述,由于某种原因,dateCells
元素的colspan不会从1变为2。
答案 0 :(得分:2)
因为你要把它添加到tr elem,请注意我已将顶部的一个更改为td并且它会扩展,也是colSpan中的大写S
function clicked(){
var cells = document.getElementsByClassName( 'cells' );
for( var i = 0; i < cells.length; i++ ){
cells[ i ].classList.remove( 'noDisplay' );
}
var dateCells = document.getElementsByClassName( 'dateCells' );
for( var r = 0; r < dateCells.length; r++ ){
dateCells[ r ].colSpan = "2";
}
}
&#13;
table td, table th{ border: 2px solid #0f0f0f; text-align:center; }
.noDisplay{ display:none; }
&#13;
<table>
<tbody>
<tr ><td colspan = "1"class = "dateCells">DATE</td></tr>
<tr><td>Cell One</td><td class = "cells noDisplay">Cell Two</td></tr>
<tr><td>Cell One</td><td class = "cells noDisplay">Cell Two</td></tr>
<tr><td>Cell One</td><td class = "cells noDisplay">Cell Two</td></tr>
<tr><td>Cell One</td><td class = "cells noDisplay">Cell Two</td></tr>
<tr class = "dateCells" ><td colspan = "1">DATE</td></tr>
<tr><td>Cell One</td><td class = "cells noDisplay">Cell Two</td></tr>
<tr><td>Cell One</td><td class = "cells noDisplay">Cell Two</td></tr>
<tr><td>Cell One</td><td class = "cells noDisplay">Cell Two</td></tr>
<tr><td>Cell One</td><td class = "cells noDisplay">Cell Two</td></tr>
</tbody>
</table>
<br>
<div onclick = "clicked()">CLICK<br>HERE</div>
&#13;
答案 1 :(得分:1)
您的脚本中需要.colSpan
。注意资本S
。另外,您需要在
dateClass
作为表格行<tr>
<td class="dateCells" colspan = "1">Date</td>
请参阅此fiddle。
答案 2 :(得分:0)
试试这个,
dateCells[ i ].colSpan = "2";