英文:
Not able to pass class attribute in innerhtml for td tag Javascript
问题
我已经开始学习HTML和JavaScript,并希望创建一些动态行。但是每当我尝试使用td标签以及类属性来设置cell.innerHTML时,我可以添加行,但类属性没有被设置。
尝试查看不同的Stack Overflow 链接:来源1
使用不同的标签(如p标签)进行类似尝试,对我来说是有效的。
期望学习如何在设置td标签时传递类属性。
英文:
I have started working on html and javascript and wanted to have some dynamic rows. But whenever I try to set cell.innerHTML with td tag along with class attributes, I am able to add rows but the class attribute is not getting set.
<!DOCTYPE html>
<html>
<head>
<style>
table, thead, td {
border:1px solid black;
}
.editMe{
color:red;
}
</style>
</head>
<body>
<button onclick="myFunction()">Try it</button>
</br></br>
<table id="simpleEditableTable" >
<thead>
   <tr>
       <th>testId</th>
   </tr>
</thead>
<tbody>
   <tr>
	    <td class="editMe">1.01</td>    
   </tr>
   <tr>
	    <td class="editMe">1.02</td>    
   </tr>   
</tbody>   
</table>
<p id="para">See</p>
<script>
function myFunction() {
  //document.getElementById("demo").innerHTML = '<td style="color:red">helo</td>';
  
			  var table = document.getElementById("simpleEditableTable");
			  var row = table.insertRow(-1);
			  var cell = row.insertCell(0);
			  cell.innerHTML='<td class="editMe">Not working</td>';
           var para = document.getElementById("para");
           para.innerHTML='<p style="color:red">working</p>';
			  //tried below ones too
			 // cell.innerHTML="<td class='editMe'>helo</td>";
  
  
  
}
</script>
</body>
</html> 
Tried going through different stackover flow links: Source1
Tried similar with different tags like p tag and its working for me.
Expecting to learn how can I pass class attribute in td tag while setting.
答案1
得分: 0
你需要设置单元格的 outerHTML 或行的 innerHTML 来修改 <td> 元素本身。
cell.outerHTML = '<td class="editMe">Some text</td>';
在这里,更适合设置 textContent 并使用 .classList.add 来更改类。
let cell = row.insertCell(0);
cell.classList.add('editMe');
cell.textContent = 'Some text';
英文:
You would need to set the cell's outerHTML or the row's innerHTML to modify the <td> element itself.
cell.outerHTML = '<td class="editMe">Some text</td>';
Here, it is more appropriate to set the textContent and use .classList.add to change the class.
let cell = row.insertCell(0);
cell.classList.add('editMe');
cell.textContent = 'Some text';
答案2
得分: 0
cell.innerHTML= <td class="editMe">Not working</td> ;
Use this `` instead not the ‘’ to enclose your text, since it’s an html tag and not a string
英文:
cell.innerHTML= <td class="editMe">Not working</td> ;
Use this `` instead not the ‘’ to enclose your text, since it’s an html tag and not a string
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论