【发布时间】:2018-03-26 01:47:11
【问题描述】:
我正在使用以下代码动态创建一个表。该表是根据需要创建的(代码有效)。这些单元格最终通过 Javascript innerHTML 填充。我需要添加两个功能,我正在寻求有关如何执行此操作的建议:
(1) 单元格 c2 和 c3 中的字体应与浏览器使用的默认字体不同。对于 c3,我尝试使用 c3.style.font = "Sans-serif"; 执行此操作,但这对字体没有影响。
(2) 当用户点击一个单元格时,我希望使用被点击的单元格的(行、列)调用 Javascript,最好不必为每个单元格添加“onClick”。
HTML:
<table id="St" cellpadding=5 cellspacing=0></table>
Javascript:
function MakeTable(nCols, nRows)
{
var table = document.getElementById("St");
for (iRow = 0; iRow < nRows; iRow++) {
var row = table.insertRow(-1); // add a row at the end
// Row will have 3 x nCols cells
for (iCol = 0; iCol < nCols; iCol++) {
var c1 = row.insertCell(-1);
c1.style.width = 16; c1.style.borderStyle = "solid";
c1.style.borderColor = "black";
c1.style.borderWidth = "thin";
var c2= row.insertCell(-1);
c2.style.width = 70; c2.style.borderStyle = "solid";
c2.style.borderColor = "black";
c2.style.borderWidth = "thin";
var c3= row.insertCell(-1);
c3.style.width = 70; c3.style.font = "Sans-serif";
c3.style.borderStyle = "solid";
if (iCol + 1 < nCols) // only separators between columns are thick
c3.style.borderWidth = "thin 3px thin thin";
else
c3.style.borderWidth = "thin";
c3.style.borderColor = "black";
}
}
}
`
【问题讨论】:
-
如果您的浏览器的默认字体是无衬线字体,那么将 font-family 更改为无衬线字体不会有任何影响。如果您的浏览器的默认字体是 serif(或 dingbats),它会产生影响。点击查看stackoverflow.com/questions/203198/…
-
使用类或选择器比将样式值单独设置为元素样式属性要好得多。
-
浏览器默认是 Times New Roman,而不是无衬线字体。但是还是没有效果。
-
@MikeMcCaughan:除了让每个单元格都有自己的“onClick”之外,我没有看到处理 Javascript(不是 jQuery)中点击的方法。
-
@RobG:您如何将类/选择器用于动态创建的元素?还是您只是指我现有代码集的表格单元格属性?
标签: javascript dynamic html-table font-face