【问题标题】:Javascript to compare 2 dates in html and change colorsJavascript 比较 html 中的 2 个日期并更改颜色
【发布时间】:2017-05-15 13:47:15
【问题描述】:

我正在使用烧瓶创建网络应用程序。

/companies.html 任务是创建一个表格,其中包含从 MongoDb 数据库(托管在 mLab 中)导入的一些文本和日期。

这里是python文件的重要部分:

@app.route('/companies', methods=['GET'])
def showCompanies():
    if 'userName' not in session:
        return redirect(url_for('start_page'))
    mongoCompanies = mongo.db.companies
    mLabCompanies = [x for x in mongoCompanies.find()]
    return render_template('companies.html', mLabCompanies=mLabCompanies)

这里是一些示例 html:

{% for theCompany in mLabCompanies %}
<tr><td>{{theCompany.companyName}}</td> <td {{theCompany.companyShouldGetANumberDate}}</td> <td>{{theCompany.companyShouldGetBNumberDate}}</td></tr>
{% endfor %}

这只是一个示例。完整版包含 114 个单元格,其中大约 20% 是日期,80% 是标准文本。 它运作良好 - 我的意思是该表已生成并填充了数据库记录。

现在我需要 js 将这些日期与今天进行比较,并在 html 中更改它们的颜色(如果日期是过去,则为红色,如果日期在未来,则为绿色)。

这是我创建的js。

<script>
function checkDate() {
    var todayDate = new Date();
    var checkedDate = Date.parse(theCompany.textContent);
    if (checkedDate > todayDate){
        theCompany.style.color = "green";
    } else {
        theCompany.style.color = "red"
    }
}
</script>
  1. JS 脚本不工作。我应该改变什么?
  2. 我应该在 html 中的哪个位置放置 JS 以使其检查每个日期并更改其颜色?

【问题讨论】:

  • 如果语法不正确,丢失 (
  • 在浏览器中打开开发控制台,有一些错误信息等着你。
  • 公司在哪里得到定义?
  • 如果存在日期,则为初学者设置一个课程,以便您只定位该课程
  • 深,Teemu - 在这里发布简单代码时犯了一些错误 - 现在应该可以使用所有 ( ) ; } 罗伯特 - 在 html 中。有没有办法让 JS 为我利用它?

标签: javascript python html date flask


【解决方案1】:

在我看来,这最好在服务器上运行,以消除本地时区日期的变幻莫测,并从客户端删除不必要的代码。

假设您有一个列中有公司名称和日期的表格,并且您希望根据日期是否在未来为日期单元格着色。所以你需要一种方法,首先获取公司单元格,然后找到相关的日期单元格,然后对单元格进行适当的着色。

您可以使用带有选择器的查询来获取公司名称,我建议您给单元格一个类或数据属性来区分它们。日期单元格也是如此,因此很容易找到它们。您需要处理日期单元格中的值,这可能不是有效日期。您可以编写小型解析函数(见下文)或使用库。

然后在与“今天”比较后,应用一个类来改变日期单元格的颜色,例如

编辑

您似乎只想处理日期单元格而忽略公司单元格。以下是一个经过编辑的版本,它只需要注释掉 2 行并对第三行进行小幅更改(原始行保留并已被注释掉以显示更改)。

/* Parse ISO formatted date, e.g. 2017-06-30 as local
** @param {string} s - date in ISO 8601 format
** @returns {Date} will be an invalid date if string is not a valid date
*/
function parseISOasLocal(s) {
  var b = s.split(/\D/);
  var d = new Date(b[0],--b[1],b[2]);
  return d && d.getMonth() == b[1]? d : new Date(NaN);
}

// Edited to only deal with dateCells

window.onload = function(){
  // Get all the company and date cells
//  var companyCells = document.querySelectorAll('.companyName');
  var dateCells = document.querySelectorAll('.companyDate');
  var today = new Date();
  // For each company cell, get the date cell and apply a class
  // based on whether the date is in the future or not
  // Invalid dates get the same class as past dates
//  [].forEach.call(companyCells, function(cell, i) {
  [].forEach.call(dateCells, function(dateCell) {

//    var dateCell = dateCells[i];
    var d = parseISOasLocal(dateCell.textContent);
    if (!isNaN(d) && d > today) {
      dateCell.classList.add('futureDate');
    } else {
      dateCell.classList.add('pastDate');
    } 
  });
}
.futureDate {
  color: black;
  background-color: green;
}
.pastDate {
  color: black;
  background-color: red;
}

table {
  border-left: 1px solid #9999;
  border-top: 1px solid #9999;
  border-collapse: collapse;
}
td, th {
  border-right: 1px solid #9999;
  border-bottom: 1px solid #9999;
  padding: 5px 5px 5px 5px;
}
<table>
  <tr>
    <th>Company name</th>
    <th>Date</th>
  </tr>
  <tr>
    <td class="companyName">Company A</td>
    <td class="companyDate">2016-07-15</td>
  </tr>
  <tr>
    <td class="companyName">Company B</td>
    <td class="companyDate">2017-07-15</td>
  </tr>
  <tr>
    <td class="companyName">Company C</td>
    <td class="companyDate">No date</td>
  </tr>

</table>

以上处理日期单元格中的无效值(例如,对于公司 C),但依赖于公司和日期的顺序相同。无效日期获得与过去日期相同的类,可以使用if (isNaN(d)) 将它们挑出并赋予不同的类。

使用展开语法,onload 函数体可以是:

var today = new Date();
[...document.querySelectorAll('.companyDate')].forEach(cell => 
  cell.classList.add(parseISOasLocal(cell.textContent) > today? 'futureDate':'pastDate')
);

但网络可能还没有为此做好准备。

【讨论】:

  • 谢谢。它可以工作,但会产生一个错误。整列是红色而不是一个单元格。现在我正在尝试修复它。
  • 我想通了。没有错误。整个列变红了,因为根据此脚本没有日期变红。就是这样——这个案子已经结束了。
  • 如果没有“companyName”单元格,如何更改此功能? html 表格中只有“companyDate”单元格。
  • @Nick493 — 您可以删除对 companyName 单元格的任何引用并遍历 companyDate 单元格,这实际上更简单。我假设你包含了 companyDate 单元格,因为你打算对它们做与问题无关的其他事情。
【解决方案2】:

JavaScript 有几个语法错误。看起来您需要将保存在theCompany.textContent 中的日期字符串转换为日期,以便将其与todayDate 进行比较。为此,您需要使用 Date.parse()

这是一个更正的版本:

<script>
  function checkDate() {
    var todayDate = new Date();

    // Depending on what "theCompany" is, this still may not work
    // It looks like it is an HTML element, in which case, you will
    // need to extract the content of the element (i.e. theCompany.textContent)
    // and then you'll need to make a new data from that string of data
    // before you try to compare it to "todayDate" with 
    // "Date.parse(valid date string here)"
    var checkedDate = Date.parse(theCompany.textContent);
    if (checkedDate > todayDate){
         theCompany.style.color = "green";
    } else {
         thCompany.style.color = "red"
    }
  }
</script>

【讨论】:

  • 在 Python 中使用 theCompany 怎么样?
  • 如何检查所有内容?语法只是 OP 问题的一部分
  • @Teemu 我对 Python 一无所知,所以我说它看起来像 Date.parse() 是必需的。 OP 正在设置theCompany.style,所以看起来theCompany 是一个DOM 对象。
  • 我也没有,但是第一个 sn-p 中的{% for theCompany in mLabCompanies %} 显示,theCompany 是在服务器端定义的?
  • @Teemu 我确实看到了,但是 OP 试图设置 theCompany.style 的事实让我相信它是一个 DOM 元素。也许它是来自 Python 的 DOM 元素?或者,也许该行不是从 Python 获取的,而是将其发送到 Python?
猜你喜欢
  • 1970-01-01
  • 2011-10-17
  • 1970-01-01
  • 2022-11-18
  • 1970-01-01
  • 1970-01-01
  • 2015-08-22
  • 1970-01-01
  • 2016-03-31
相关资源
最近更新 更多