使用动态表的静态/粘性页眉



请有人指导我如何为这个动态创建的表实现静态(粘性(头?

一段时间以来,我已经尝试了Stackoverflow线程的多种功能,但缺乏HTML/CSS知识,显然我缺少了一些简单的东西。

我已经设法使用直接在代码主体中创建的表使其工作,但当我使用从JSON动态创建的表时,我无法获得任何东西。

代码下方:

<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=0.50, maximum-scale=1, user-scalable=0"/>
<head>
<title>iNews HTML Running Order</title>
<style>
table 
{
border: solid 1px #CCCCCC;
border-collapse: collapse;
text-align: left;
font:30px Arial;
}
tr, th, td
{
white-space: nowrap;
padding-right: 50px;
}
tr
{
background-color: #ffffff;
border: solid 1px #CCCCCC;
}
th
{
background-color: #CCCCCC;
}
#container
{
text-align: center;
max-width: 100%;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body onload="initialisePage('LW')">
<p id="showData">Loading Running Order...</p>

</body>

<script>
var loop;
var filename;
var table;
function updateJSONData(filename)
{
getDataFromJSON(filename)
loop = setInterval(function(){getDataFromJSON(filename);}, 500);
}
function initialisePage(newFilename)
{
filename = newFilename;
updateJSONData(filename)
}
function setFileName(newFilename)
{
clearInterval(loop)
filename = newFilename;
updateJSONData(filename)
}
function getDataFromJSON(filename)
{
$.get( "http://10.142.32.72/dashboard/"+filename+".json", function( data ) {
var myBooks = JSON.parse(data);
CreateTableFromJSON(myBooks)
});
}
function CreateTableFromJSON(myBooks)
{
var title = ["Page", "Slug", "Pres 1", "Pres 2", "CAM", "Format", "Clip Dur", "Total", "Backtime"];
var col = ["page-number", "title", "pres1", "pres2", "camera", "format", "runs-time", "total-time", "back-time"];
// CREATE DYNAMIC TABLE.
table = document.createElement("table");
// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
var tr = table.insertRow(-1);                   // TABLE ROW.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th");      // TABLE HEADER.
th.innerHTML = title[i];
tr.appendChild(th);
}
// ADD JSON DATA TO THE TABLE AS ROWS.
for (var i = 0; i < myBooks.length; i++) {
tr = table.insertRow(-1);
if (myBooks[i]["floated"] == "true"){
tr.style.color = "#ffffff";
tr.style.background = "blue";
}
if ((myBooks[i]["break"] == "true") && (myBooks[i]["floated"] == "false")){
tr.style.background = "#00ff00";
}
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = myBooks[i][col[j]];
}
}
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
console.log("Refreshed: " + filename);
}
</script>
</html>

非常感谢,

Joe

  • 删除<body onload="initialisePage('LW')">并使用DOMContentLoaded,因为它发生得比文档load事件早得多。

    • load只有在加载了所有资源/内容之后才会触发,包括图像等"非必需"(非DOM(内容和广告横幅等外部内容,这意味着load事件可能会在DOMContentLoaded之后几十秒触发,这使得load事件在今天有点无用(
  • 将您的CSS更改为:

    table > thead > tr > th {
    position: sticky;
    top: 0;
    z-index: 10;
    }
    table > tbody > tr.floated {
    color: '#ffffff';
    background-color: 'blue';
    }
    table > tbody > tr.broken {
    background-color: '#00ff00';
    }
    
  • JavaScript将camelCase用于函数、值(变量和参数(和属性,而不是PascalCase

  • 避免使用var,并在适当的情况下在脚本中使用constlet。注意,const的意思是"不变的引用"(有点像C++(;它不意味着"不可变"或"编译时常数值"。我认为const的定义是JavaScript语言设计者的一个错误,但这只是,我的看法,伙计
  • 通过classList使用CSS类,而不是使用.style设置单独的样式属性
  • 当前的JavaScript生态系统通常也使用1TBS,而不是Allman风格
  • 首选===(恰好等于(而不是==(等于(,因为JavaScript的类型强制可能令人惊讶(
  • 尽可能避免使用innerHTML。使用.textContent设置正常文本内容(同时避免使用.innerText(。滥用innerHTML会导致XSS漏洞
  • 现在是2020年。停止使用JQUERY!!!!!!!!!!
    • 引用
    • Cite
    • Cite
    • Cite
  • 不要在JAVASCRIPT评论中使用全大写,因为看起来作者在对你大喊大叫,这对其他读者来说很烦人
  • 您需要正确处理HTTP请求响应(例如,使用正确的Content-Type检查成功的响应(
  • 避免使用j作为可迭代变量名,因为它在视觉上与i过于相似
  • 将您的JavaScript更改为:

    <script>
    // You should put all of your own application-specific top-level page script variables in their own object so you can easily access them separately from the global `window` object.
    const myPageState = {
    loop    : null,
    fileName: null,
    table   : null
    };
    window.myPageState = myPageState; // In the top-level function, `const` and `let`, unlike `var`, do not create a global property - so you need to explicitly set a property like so: `window.{propertyName} = ...`.
    window.addEventListener( 'DOMContentLoaded', onDOMLoaded );
    function onDOMLoaded( ev ) {
    window.myPageState.fileName = "LW";
    window.myPageState.loop = setInterval( refreshTable, 500 );
    }
    async function refreshTable() {
    if( typeof window.myPageState.fileName !== 'string' || window.myPageState.fileName.length === 0 ) return;
    const url = "http://10.142.32.72/dashboard/" + window.myPageState.fileName + ".json";
    const resp = await fetch( url );
    if( resp.status === 200 && resp.headers['ContentType'] === 'application/json' ) {
    const deserialized = await resp.json();
    ceateAndPopulateTableFromJSONResponse( deserialized );
    }
    else {
    // Error: unexpected response.
    // TODO: error handling
    // e.g. `console.error` or `throw new Error( "Unexpected response." )`, etc.
    }
    }
    function ceateAndPopulateTableFromJSONResponse( myBooks ) {
    // TODO: Verify the `myBooks` object layout (i.e. schema-verify `myBooks`).
    const columnTitles = ["Page", "Slug", "Pres 1", "Pres 2", "CAM", "Format", "Clip Dur", "Total", "Backtime"];
    const columnNames = ["page-number", "title", "pres1", "pres2", "camera", "format", "runs-time", "total-time", "back-time"];
    const table = window.myPageState.table || document.createElement( 'table' );
    if( window.myPageState.table !== table ) {
    window.myPageState = table;
    document.getElementById("showData").appendChild( table );
    }
    // Create the <thead>, if nnecessary:
    if( table.tHead === null )
    {
    table.tHead = document.createElement( 'thead' );
    const tHeadTR = table.tHead.insertRow(-1);
    for( let i = 0; i < columnNames.length; i++ ) {
    const th = document.createElement('th');
    th.textContent = columnTitles[i];
    tHeadTR.appendChild( th );
    }
    }
    // Clear any existing tbody:
    while( table.tBodies.length > 0 ) {
    table.removeChild( table.tBodies[0] );
    }
    // Populate a new <tbody>:
    {
    const tbody = document.createElement('tbody');
    for( let i = 0; i < myBooks.length; i++ ) {
    const tr = table.insertRow(-1);
    tr.classList.toggle( 'floated', myBooks[i]["floated"] === "true" );
    tr.classList.toggle( 'broken' , myBooks[i]["break"  ] === "true" && myBooks[i]["floated"] === "false" );
    for( let c = 0; c < columnNames.length; c++ ) {
    const td = tr.insertCell(-1);
    const colName = columnNames[c];
    td.textContent = myBooks[i][ colName ];
    }
    }
    table.appendChild( tbody );
    }
    console.log( "Refreshed: " + window.myPageState.fileName );
    }
    </script>
    

相关内容

  • 没有找到相关文章

最新更新