Javascript根据MySQL日期值和今天为行着色

时间:2019-07-09 16:43:40

标签: javascript mysql

我正在页面上显示MySQL表结果,并且试图突出显示“下一个审阅日期”早于今天日期的行,这些行应被涂成红色(后来我也希望今天再涂另一种颜色) +10天应为橙色)。我知道我需要为此使用Javascript,但是,我尝试了10多种解决方案,但没有一个起作用,您能帮我吗?下次审核日期采用phpmyadmin(YYYY-MM-DD)中的日期格式。

这是我目前尝试过的内容(表的ID为table):

var table = document.getElementById("table");
      for(var i = 0; i < table.rows.length; i ++) {
        var status = new Date(table.rows[i].cells[4].innerHTML).getTime();
        var now = new Date().getTime();
        console.log(now>status)
        if (now>status) { 
            table.rows[i].style.background = "red";
        } 
        };

如果您需要更多代码或说明,请指出,然后我将对其进行编辑。非常感谢您的帮助!

这是表格现在的样子(着色从未成功):

if ($_SESSION['user_type'] == 'admin') {
    echo '<div class="table" id="table"> <table>
        <tr>
        <th>
            <a href="?orderBy=name">Asset name</a>
        </th>
        <th>
            <a href="?orderBy=classification">Classification</a>
        </th>   
        <th>
            <a href="?orderBy=tag">Tag</a>
        </th>
        <th>
            <a href="?orderBy=department">Department</a>
        </th>   
        <th>
            <a href="?orderBy=nextreview">Next review date</a>
        </th>   
        <th>
            <a href="?orderBy=responsible">Responsible</a>
        </th>   
        <th>Update</th>
        </tr>';


    $sql = "SELECT * 
    FROM `assets`
    ORDER BY id";

    if (isset($_GET['orderBy'])) {
        $orderby = $_GET['orderBy'];

        if ($orderby == 'name')
        {
            $sql = "SELECT * FROM `assets`ORDER BY Asset_name";
        }
        elseif ($orderby == 'classification')
        {
            $sql = "SELECT * FROM `assets`ORDER BY Classification";
        }
        elseif ($orderby == 'tag')
        {
            $sql = "SELECT * FROM `assets`ORDER BY Tag";
        }
        elseif($orderby == 'department')
        {
            $sql = "SELECT * FROM `assets`ORDER BY Department";
        }
        elseif($orderby == 'nextreview')
        {
            $sql = "SELECT * FROM `assets` ORDER BY Review_date asc";
        }
        elseif($orderby == 'responsible')
        {
            $sql = "SELECT * FROM `assets`ORDER BY Responsible";
        }
    }
    if (!($result=mysqli_query($conn, $sql)))
    { die("Could not show the required data" . mysqli_error($conn));}
    elseif (mysqli_num_rows($result) > 0) {

        while($result2=mysqli_fetch_array($result))
        {echo '<tr>
        <td>'.$result2["Asset_name"].'</td>
        <td>'.$result2["Classification"].'</td>
        <td>'.$result2["Tag"].'</td>
        <td>'.$result2["Department"].'</td>
        <td class="status">'.$result2["Review_date"].'</td>
        <td>'.$result2["Responsible"].'</td>
        <td><a href="editassets.php?id='.$result2['id'].'">Edit</a> | <a href="deleteassets.php?id='.$result2['id'].'" onclick="return confirm(\'Do you want to delete this asset?\');">Delete</a></td>
        </tr>';
        }
        echo '</table></div>';
        }

当前外观:

2 个答案:

答案 0 :(得分:0)

  • 应具有表的ID,而不是包装器-请将TH封装在THEAD中,并将表的其余部分封装在TBODY中
  • 我使用类而不是背景色
  • 我使用querySelectorAll直接获取单元格
  • 我使用字符串比较。比日期比较快
  

向下滚动到与旧版IE兼容的版本
  向下滚动以获得可排序的表格

// setup
const pad = (num) => ("0" + num).slice(-2);
const now = new Date();
const nowString = now.getFullYear() + "-" + pad(now.getMonth() + 1) + "-" + pad(now.getDate());

// loop
// remove closest("tr"). to just highlight the cell

[...document.querySelectorAll("table tr td:nth-child(5)")].forEach(cell =>
  cell.closest("tr").classList.toggle("red", nowString > cell.textContent.trim())
);
.red {
  background-color: red
}

table {
  border-collapse: collapse;
}

td {
  border: none;
}

tr  th, td {
  border: 1px solid black;
  padding: 4px;
}
<table id="table">
  <thead>
    <tr>
      <th><a href="?orderBy=name">Asset name</a></th>
      <th><a href="?orderBy=classification">Classification</a></th>
      <th><a href="?orderBy=tag">Tag</a></th>
      <th><a href="?orderBy=department">Department</a></th>
      <th><a href="?orderBy=nextreview">Next review date</a></th>
      <th><a href="?orderBy=responsible">Responsible</a></th>
      <th>Update</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td>2019-07-08</td>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td>2019-07-09</td>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td>2019-07-10</td>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td>2019-07-11</td>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td>2021-07-10</td>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td>2022-07-11</td>
      <td></td>
      <td></td>
    </tr>
  </tbody>
</table>

ES <5版本

// setup
var pad = (num) => ("0" + num).slice(-2);
var now = new Date();
var nowString = now.getFullYear() + "-" + pad(now.getMonth() + 1) + "-" + pad(now.getDate());

// loop

var cells = document.querySelectorAll("table tr td:nth-child(5)")

for (var i=0;i<cells.length;i++) {
  var row = cells[i].parentNode; // use cells[i].classList to just highlight the cell
  row.classList.toggle("red", nowString > cells[i].textContent.trim())
}
.red {
  background-color: red
}

table {
  border-collapse: collapse;
}

td {
  border: none;
}

tr  th, td {
  border: 1px solid black;
  padding: 4px;
}
<table id="table">
  <thead>
    <tr>
      <th><a href="?orderBy=name">Asset name</a></th>
      <th><a href="?orderBy=classification">Classification</a></th>
      <th><a href="?orderBy=tag">Tag</a></th>
      <th><a href="?orderBy=department">Department</a></th>
      <th><a href="?orderBy=nextreview">Next review date</a></th>
      <th><a href="?orderBy=responsible">Responsible</a></th>
      <th>Update</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td>2019-07-08</td>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td>2019-07-09</td>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td>2019-07-10</td>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td>2019-07-11</td>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td>2021-07-10</td>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td>2022-07-11</td>
      <td></td>
      <td></td>
    </tr>
  </tbody>
</table>

可疑

Sorting HTML table with JavaScript

请注意,此处的数字单元格将按字母顺序排序,需要更多代码来处理下面的90

// setup
const pad = (num) => ("0" + num).slice(-2);
const now = new Date();
const nowString = now.getFullYear() + "-" + pad(now.getMonth() + 1) + "-" + pad(now.getDate());

// loop
// remove closest("tr"). to just highlight the cell

[...document.querySelectorAll("table tr td:nth-child(5)")].forEach(cell =>
  cell.closest("tr").classList.toggle("red", nowString > cell.textContent.trim())
);

function sortTable(table, col, reverse) {
    var tb = table.tBodies[0], // use `<tbody>` to ignore `<thead>` and `<tfoot>` rows
        tr = Array.prototype.slice.call(tb.rows, 0), // put rows into array
        i;
    reverse = -((+reverse) || -1);
    tr = tr.sort(function (a, b) { // sort rows
        return reverse // `-1 *` if want opposite order
            * (a.cells[col].textContent.trim() // using `.textContent.trim()` for test
                .localeCompare(b.cells[col].textContent.trim())
               );
    });
    for(i = 0; i < tr.length; ++i) tb.appendChild(tr[i]); // append each row in order
}
function makeSortable(table) {
    var th = table.tHead, i;
    th && (th = th.rows[0]) && (th = th.cells);
    if (th) i = th.length;
    else return; // if no `<thead>` then do nothing
    while (--i >= 0) (function (i) {
        var dir = 1;
        th[i].addEventListener('click', function () {sortTable(table, i, (dir = 1 - dir))});
    }(i));
}
makeSortable(document.getElementById("table"))
.red {
  background-color: red
}

table {
  border-collapse: collapse;
}

td {
  border: none;
}

tr  th, td {
  border: 1px solid black;
  padding: 4px;
}
<table id="table">
  <thead>
    <tr>
      <th>Asset name</th>
      <th>Classification</th>
      <th>Tag</th>
      <th>Department</th>
      <th>Next review date</th>
      <th>Responsible</th>
      <th>Update</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>B</td>
      <td>200</td>
      <td></td>
      <td></td>
      <td>2019-07-08</td>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <td>A</td>
      <td>100</td>
      <td></td>
      <td></td>
      <td>2019-07-10</td>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <td>Q</td>
      <td>111</td>
      <td></td>
      <td></td>
      <td>2019-07-11</td>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <td>Z</td>
      <td>302</td>
      <td></td>
      <td></td>
      <td>2021-07-10</td>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <td>V</td>
      <td>90</td>
      <td></td>
      <td></td>
      <td>2022-07-11</td>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <td>N</td>
      <td></td>
      <td></td>
      <td></td>
      <td>2019-07-09</td>
      <td></td>
      <td></td>
    </tr>
    
  </tbody>
</table>

答案 1 :(得分:0)

当其他人开始回答时,我将在评论中发布与您讨论的内容

您的HTML具有:

<div class="table" id="table"> <table>

您的JavaScript但是定义了:

var table = document.getElementById("table");

...,并继续将table视为表元素,但事实并非如此。在您的HTML中,您可以看到它是<div>元素,而不是<table>元素。

因此将两者对齐。请更改HTML,以使<table>具有id="table"

<div class="table"> <table  id="table">

...或更改您的JavaScript,以使其使用具有该ID的<div> child 元素:

var table = document.getElementById("table").firstElementChild;

注意:请不要同时进行两项更改:选择最适合您的一项。