根据我对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。 最佳答案
因为您是将其添加到问题中,所以请注意,我仅将顶部更改为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/