根据我对 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>
正如您在上面所看到的,由于某种原因,dateCells
元素的 colspan 没有从 1 更改为 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";
}
}
table td, table th{ border: 2px solid #0f0f0f; text-align:center; }
.noDisplay{ display:none; }
<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>
关于javascript - 为什么我不能使用 .colspan 设置该元素的 colspan?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28036251/