function testit(){
document.getElementById("th1").style.textAlign = "right";
}

#th1{
text-align:left;
}

<table>
		 <tr><center><th colspan="2" id="th1">EmergencyImportantContactsnumbers</th><center></tr>
		 <tr><th colspan="2" id="th1" >Emergency.SQUCampus</tr></tr>
		 <tr><th>Emergency.m1</th><th id="th1" >Emergency.m2</th><tr>
		 <tr><td>Emergency.m3</td><td id="th1" >Emergency.m4</td></tr>
		 <tr><td>Emergency.m5</td><td id="th1" >Emergency.m6</td></tr>

		 </table>
<button onclick="testit();">Text Script</button>





我想更改表格中单元格的文本对齐方式。我已经使用JavaScript来更改文本对齐方式。当我重新编辑样式代码时,它不起作用。

我想将文本对齐方式更改为正确。但是我的代码无法正常工作。
请帮我谢谢你。

最佳答案

像这样:

HTML:

<table>
         <tr><center><th colspan="2" class="th1">EmergencyImportantContactsnumbers</th><center></tr>
         <tr><th colspan="2" class="th1" >Emergency.SQUCampus</tr></tr>
         <tr><th>Emergency.m1</th><th class="th1" >Emergency.m2</th><tr>
         <tr><td>Emergency.m3</td><td class="th1" >Emergency.m4</td></tr>
         <tr><td>Emergency.m5</td><td class="th1" >Emergency.m6</td></tr>
</table>


使用类而不是ID。

CSS:

table{
  width: 400px;
}
.th1{
  text-align:left;
  padding: 3px;
  border: 1px solid black;
}


JS:

var th1 = document.getElementsByClassName("th1");
for (var i = 0; i < th1.length; i += 1) {
    th1[i].style.textAlign = "right";
}

09-13 03:20