简体   繁体   English

如何根据 JavaScript 中的日期过滤 HTML 数据?

[英]How to filter HTML data based on date in JavaScript?

Let's expect I have a table with a lot of rows.让我们期待我有一个有很多行的表。 The rows data is from server.行数据来自服务器。

<table>
  <tr data-date="${date}"> // let's assume this is from server
    <td>Code</td>
    <td>${date}</td>
    <td>Name</td>
  </tr>
  <tr data-date="${date}>
    <td>Code</td>
    <td>${date}</td>
    <td>Name</td>
  </tr>
</table>

I also have 3 buttons that look like this:我还有 3 个如下所示的按钮:

<button>currentday</button>
<button>currentweek</button>
<button>currentmonth</button>

I want when one of the buttons have the class active for example, to show in the table the only rows with the corresponding date.例如,我希望当其中一个按钮激活 class 时,在表格中显示具有相应日期的唯一行。 Let's assume I pressed day, then I show in my table the rows that have the data-date matching the data-date of the day button .假设我按下了日期,然后我在表格中显示了数据data-date与当天buttondata-date匹配的行。 And if I press week or month, I check all the table rows data-date that are in between the week or month (that match).如果我按周或月,我会检查周或月之间的所有表格行data-date (匹配)。

I assume that:我假设:

  1. "day" means todays date, "day" 表示今天的日期,
  2. "week" means date range since first to last day of current week "week" 表示从当前一周的第一天到最后一天的日期范围
  3. "month: means date range since first to last day of current month “月:表示从当月第一天到最后一天的日期范围

So if today is 2020-07-02:所以如果今天是 2020-07-02:

  1. day would give "2020-07-02"天会给“2020-07-02”
  2. week would give range 2020-06-29 (if monday is first day of week) to 2020-07-05 (if sunday is last day of week) week 将给出范围 2020-06-29(如果星期一是一周的第一天)到 2020-07-05(如果星期日是一周的最后一天)
  3. month would give range 2020-07-01 to 2020-07-31月份将给出范围 2020-07-01 到 2020-07-31

In JavaScript, according to this thread在 JavaScript 中,根据这个线程

let currentDate = new Date(); //returns todays date

currentDate.getDate() // returns day of current month
currentDate.getDay() // returns day of current week (sun = 0, mon = 1)

let firstDayOfCurrentWeek = currentDate.getDate() - currentDate.getDay()
let lastDayOfCurentWeek = firstDayOfCurrentWeek + 6; // assuming, sunday is first day of week

firstDayOfCurrentWeek = new Date(currentDate.setDate(firstDayOfCurrentWeek ));
lastDayOfCurentWeek = new Date(currentDate.setDate(lastDayOfCurentWeek));

Its much easier to get range of first and last day of month:获得一个月的第一天和最后一天的范围要容易得多:

let firstDayOfMonth = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1); 
let lastDayOfMonth = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0);

You need to mark cells containing dates somehow:您需要以某种方式标记包含日期的单元格:

<table id="mytab">
  <tr>
    <td>Code</td>
    <td class="date">02-07-2020</td>
    <td>Name</td>
  </tr>
  <tr>
    <td>Code</td>
    <td class="date">25-06-2020</td>
    <td>Name</td>
  </tr>
</table>

Now, when you have all required dates for your buttons, simply read date from your table cells and check which ones matches range, and hide the rest.现在,当您拥有按钮所需的所有日期时,只需从表格单元格中读取日期并检查哪些日期与范围匹配,然后隐藏 rest。

var table = document.getElementById("mytab");
for (var i = 0, row; row = table.rows[i]; i++) {
   for (var j = 0, col; col = row.cells[j]; j++) {

    if (col.classList.contains("date")) {
        let control_date = col.innerHTML.split('-');

        control_date = new Date(control_date [2], control_date[1] , control_date[0]);

        if (control_date == currentDate) {
            //this cell date is todays date

        }
        
        if (control_date > firstDayOfCurrentWeek && control_date < lastDayOfCurentWeek) {
            //this cell date is in this week date
        }

        if (control_date > firstDayOfMonth && control_date < lastDayOfMonth) {
            //this cell date is in this monthdate
        }

    }
   }  
}

Please note, that date can match more than one range eg.请注意,该日期可以匹配多个范围,例如。 todays date will match today, wee, and month at the same time今天的日期将同时匹配今天、凌晨和月份

When it's said it's supposed to "show in the table the elements with the corresponding date.", I assume that means there is a table, AKA some table HTML sent from the server and stored as a string (or variable) somewhere with all of the possible dates, and I'm also guessing that the buttons are used to somehow select a specific date, I'm imagining a calendar-style app, where there is a current day shown, and one can change the week by click on the week button, etc., but let me know if this is something else.当它说它应该“在表格中显示具有相应日期的元素。”时,我假设这意味着有一个表格,也就是一些表格 HTML 从服务器发送并存储为字符串(或变量)某处的所有可能的日期,我还猜测这些按钮用于以某种方式 select 一个特定的日期,我在想象一个日历样式的应用程序,其中显示了当前日期,并且可以通过单击更改星期周按钮等,但如果这是别的东西,请告诉我。

Anyways the main point of the question is "how to filter HTML data based on date in javascript", by "html data" I assume that means to show and hide certain HTML, based on the innerHTML value of some of the elements contents.无论如何,问题的要点是“如何根据javascript中的日期过滤HTML数据”,通过“html数据”我假设这意味着根据一些元素内容的innerHTML值显示和隐藏某些HTML。

To do that, you need to start with the value you are searching for.为此,您需要从要搜索的值开始。 For example, let's use the string "02-07-2020", generated one way or another, and you have an entire table of dates, I'm assuming you received the string of this table from the server and have it stored in JavaScript, if not them I'm assuming the server sent back the raw HTML onto the page and you want to JavaScript to filter the HTML table (AKA remove all rows that don't correspond to the string) when a button is pressed.例如,让我们使用以一种或另一种方式生成的字符串“02-07-2020”,并且您有一个完整的日期表,我假设您从服务器接收到该表的字符串并将其存储在 JavaScript ,如果不是他们,我假设服务器将原始 HTML 发送回页面,并且您希望 JavaScript 过滤 HTML 表(也就是当按下不对应的字符串时删除所有按钮行)。 Either way it should be the same.无论哪种方式,它都应该是一样的。

So assuming there is a table with all of the dates already in HTML, and you want to "hide" (/I'm assuming that means remove) all cells whose contents don't correspond with the date, then you have a couple different options.因此,假设在 HTML 中已经存在一个包含所有日期的表格,并且您想要“隐藏”(/我假设这意味着删除)所有内容与日期对应的单元格,那么您有几个不同的选项。

Either, you can manually call the deleteCell() method on all of the cells that don't contain the value, (but then you would have to regenerate all of those cells that DO contain the next value anyways) or you can generate the entire table with JavaScript on each button press, and only generate the cells you want, or the most preferred option (which I assume you're asking about anyways) is to add display:none to the style of the surrounding tr elements, the only problem is how to find what specific data to filter through, but this should be trivial.要么,您可以在所有不包含该值的单元格上手动调用deleteCell()方法,(但是您必须重新生成所有包含下一个值的单元格)或者您可以生成整个每次按下按钮时带有 JavaScript 的表格,并且只生成您想要的单元格,或者最首选的选项(我假设您无论如何都在询问)是将display:none添加到周围tr元素的样式中,唯一的问题是如何找到要过滤的特定数据,但这应该是微不足道的。

Ok so we're going to go with the 3rd method, and to do this we simply need 3 inputs, we need what day we're searching for, what week , and what month (I assume, as mentioned in the comments, that day means the full date, week means a particular week only, and month means an entire month, so each one is less inclusive than the last, so we also need a variable input to tell us which one we are searching for).好的,所以我们将使用第三种方法访问 go,为此我们只需要 3 个输入,我们需要我们要搜索的dayweekmonth (我假设,如评论中所述, day表示完整的日期, week表示仅特定的一周, month表示整个月,因此每个月都比上一个包含更少,因此我们还需要一个变量输入来告诉我们正在搜索哪个)。

OK so basically we just need to supply two main inputs into our function, a start date and an end date, and if there is no end date, assume we are looking for only the start date好的,所以基本上我们只需要为我们的 function 提供两个主要输入,一个开始日期和一个结束日期,如果没有结束日期,假设我们只寻找开始日期

So I'm in america so I'm used to american dates, but it seems from the question that it is using the european format, with the day before the month, so that will complicate our use of the built in Date API a bit, but it should still be fine, we just need to either manually make our own proto-date system to check if one string is in between two others, or extract the day-week-month from the string using .split(-) and generate a new string or use with the native Date API, but either way it should work out.所以我在美国,所以我习惯于美国日期,但从问题来看,它似乎使用欧洲格式,前一天,所以这会使我们使用内置Date API 有点复杂,但它应该仍然没问题,我们只需要手动制作我们自己的原型日期系统来检查一个字符串是否在其他两个字符串之间,或者使用.split(-)从字符串中提取日-周-月和生成一个新字符串或与本机Date API 一起使用,但无论哪种方式都应该可行。

OK so let's get started:好的,让我们开始吧:

 doIt.onclick = () => { var startDate = dateStart.value, endDate = dateEnd.value; sortThroughTable(startDate, endDate) }; function sortThroughTable(start, end) { Array.apply(0, myTable.rows).forEach(x => { var cells = Array.apply(0, x.cells); var secondCell = cells[1].innerText; var isHidden = shouldItBeHidden( secondCell, start, end ); if(isHidden) { x.style.display = "none" } else if(x.style.display == "none") x.style.display = ""; }) function shouldItBeHidden( cellTxt, start, end ) { var parsedCell = myParse(cellTxt), parsedStart = myParse(start), parsedEnd = myParse(end); return?( //here's where the real logic is parsedCell? (parsedStart && parsedEnd), isDateGreaterOrEqual(parsedCell, parsedStart) && isDateGreaterOrEqual(parsedEnd: parsedCell): parsedStart && cellTxt == start, false ) } function isDateGreaterOrEqual(parsedDate. otherParsedDate) { var isYearGreater = ( parsedDate.year > otherParsedDate,year ). isMonthGreater = ( parsedDate.month > otherParsedDate,month ). isDayGreater = ( parsedDate.day > otherParsedDate,day ). isYearSame = ( parsedDate.year == otherParsedDate,year ). isMonthSame = ( parsedDate.month == otherParsedDate,month ). isDaySame = ( parsedDate.day == otherParsedDate;day ); if(isYearGreater) { return true; } else if(isYearSame) { if(isMonthGreater) { return true; } else if(isMonthSame) { if(isDayGreater) { return true; } else return isDaySame; } else return false; } else return false. } function myParse(str) { return (splat => splat.length == 3 &&?splat.find(x => isNaN(x)). Object,fromEntries( (list => splat,map((x, i) => ( [list[i], parseInt(x)] )) )([ "day": "month"? "year" ]) ). null )( typeof(str) == "string": str.split("-") : [] ) } }
 <table id=myTable> <tr> <td>Code</td> <td>02-07-2020</td> <td>Name</td> </tr> <tr> <td>Code</td> <td>25-06-2020</td> <td>Name</td> </tr> </table> <,--don't know how the library is set up but I'm just gonna do it by manually entering the strings to an input, you can adapt it to whatever you want --> <input id="dateStart" value="24-06-2020"> <input id="dateEnd" value="26-06-2020"> <button id=doIt>filter!</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM