动态创建表格中的粗体文字 - javascript

时间:2018-05-27 21:50:08

标签: javascript

我尝试使用javascript中的.bold()方法将粗体文本添加到表标题行。该表是使用以下代码动态创建的:

var table = document.getElementById('changestable');
    var titlerow = ["Type", "Change Date", "FCM", "Hull ID", "Name", "Length", "Manufacturer", "Manufacturer ID", "Year", "Value", "Owner", "Loss Payee", "Policy ID", "Start Date", "End Date"];
    var newRow = table.insertRow(0);
    for (k = 0; k < titlerow.length; k++){
        var newCell = newRow.insertCell(k);
        var newText = document.createTextNode(titlerow[k]);
        newCell.appendChild(newText);
    }

我试过了:

.bold() // and this just adds <b></b>, not actually making the text bold

我也尝试过:

titlerow[k].style.fontWeight = 'bold'

提前谢谢!

2 个答案:

答案 0 :(得分:2)

您无法将ember-console.js:29 Error while processing route: todos Ember Data Request GET /todos returned a 404 应用于字符串 - 您必须将其应用于元素。

style

但是,为什么不在CSS中应用样式,而不是试图在Javascript中混淆它?将Javascript功能与页面样式分开

&#13;
&#13;
newCell.style.fontWeight = 'bold';
&#13;
var table = document.getElementById('changestable');
var titlerow = ["Type", "Change Date", "FCM", "Hull ID", "Name", "Length", "Manufacturer", "Manufacturer ID", "Year", "Value", "Owner", "Loss Payee", "Policy ID", "Start Date", "End Date"];
var newRow = table.insertRow(0);
for (k = 0; k < titlerow.length; k++){
  var newCell = newRow.insertCell(k);
  var newText = document.createTextNode(titlerow[k]);
  newCell.appendChild(newText);
}
&#13;
#changestable tr:first-child {
  font-weight: bold;
}
&#13;
&#13;
&#13;

或者,更好的是,如果可能的话,请插入<table id="changestable"></table>而不是th,并且您根本不需要样式,因为td是自动加粗:

&#13;
&#13;
th
&#13;
var table = document.getElementById('changestable');
var titlerow = ["Type", "Change Date", "FCM", "Hull ID", "Name", "Length", "Manufacturer", "Manufacturer ID", "Year", "Value", "Owner", "Loss Payee", "Policy ID", "Start Date", "End Date"];
var newRow = table.insertRow(0);
titlerow.forEach(titleStr => {
  newRow.appendChild(document.createElement('th'))
    .textContent = titleStr;
});
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以使用innerHTML并添加<b>代码

for (k = 0; k < titlerow.length; k++){
    var newCell = newRow.insertCell(k);
    var newText = document.createTextNode();
    newText.innerHTML = `<b> ${titlerow[k]} </b>`;
    newCell.appendChild(newText);
}