[英]How to insert space in table cell when generating table dynamically by javascript
i wrote a code to test one issue and notice that not being able to add space when generating table with data dynamically by javascript. 我编写了一个代码来测试一个问题,并注意到在通过JavaScript动态生成带有数据的表时无法添加空间。
i use to add some space but did not work. 我用来添加一些空间,但是没有用。
<div id='table'>
</div>
var array = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];
var arrayLength = array.length;
var theTable = document.createElement('table');
// Note, don't forget the var keyword!
for (var i = 0, tr, td; i < arrayLength; i++) {
tr = document.createElement('tr');
td = document.createElement('td');
td.appendChild(document.createTextNode('<span>'+array[i].id+' </span>'));
tr.appendChild(td);
td = document.createElement('td');
td.appendChild(document.createTextNode('<span>'+array[i].foo+' </span>'));
tr.appendChild(td);
theTable.appendChild(tr);
}
//alert(theTable);
document.getElementById('table').appendChild(theTable);
looking for suggestion. 寻找建议。 thanks
谢谢
You can continue the same way you did with td and tr. 您可以像使用td和tr一样继续进行操作。 Create a new span element, then set the innerHTML.
创建一个新的span元素,然后设置innerHTML。
createTextNode
is just for that, text, so the browser won't interpret tags and html entities. createTextNode
仅用于表示文本,因此浏览器不会解释标签和html实体。
var span = document.createElement('span');
span.innerHTML = array[i].id+' ';
td.appendChild(span);
You can use the Unicode character for a space directly: 您可以直接将Unicode字符用于空格:
td.appendChild( document.createTextNode( '\u00A0' ) );
Can obviously be done a couple of times: 显然可以做几次:
td.appendChild( document.createTextNode( '\u00A0\u00A0\u00A0' ) );
// three spaces
You could use CSS to add some padding. 您可以使用CSS添加一些填充。
#table td > span { padding-right:20px; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.