我想过滤员工详细信息..因为我有一个包含数字和字符串的选择选项...我可以过滤对象中的字符串,但不能使其为数字...请指导我
<select id="endDate" onchange="sortEDate()">
<option value="All Years">All Years</option>
<option value="Past Years">Past Years</option>
<option value="Present">Present</option>
</select>
<p id="demo1"></p>
const employees = [
{ firstname: "Dav", start: 2013, end: 2018 },
{ firstname: "Gemmy", start: 2016, end: "Present" }
]
function sortEDate() {
const filterDate = [];
let cDate = document.getElementById("endDate").value;
employees.forEach(function(item, index, array) {
if (item.end === cDate) {
filterDate.push(item);
}
});
let fDate = "<table>";
filterDate.forEach(function(filterDate) {
fDate += "<tr>";
fDate += "<td>" + filterDate.firstname + "</td>";
fDate += "<td>" + filterDate.start + "</td>";
fDate += "<td>" + filterDate.end + "</td>";
fDate += "</tr>";
});
fDate += "</table>";
document.getElementById("demo1").innerHTML = fDate;
let allEducation = document.getElementById("endDate").value;
if (allEducation === "All Years") {
showEmployees();
}
}
答案 0 :(得分:0)
在下面的内容中,如果使用block,请尝试使用==
而不是===
if (item.end == cDate) {
filterDate.push(item);
}
答案 1 :(得分:0)
我进行了一些更改以使此工作按预期进行。我为label
元素使用了value
和option
,并将实际选择的值传递给select onchange
处理程序。我也将项目加载到了load
的主体上,您可以将其删除,我只是希望它们在页面加载等时被加载。由于您没有使用jQuery,因此它位于onload
事件处理程序等上。
const employees = [{
firstname: "Dav",
start: 2013,
end: 2018
},
{
firstname: "Gemmy",
start: 2016,
end: "Present"
}
]
function filterDates(sel) {
let filterDate = []
sel = sel || "All"
filterDate.push(...employees.filter(function(obj) {
switch (sel) {
case "All":
return true // return all
case "Past":
return obj.end < new Date().getFullYear() // just past years
case "Present":
return obj.end === 'Present'
}
}))
let fDate = "<table>";
filterDate.forEach(function(filterDate) {
fDate += "<tr>";
fDate += "<td>" + filterDate.firstname + "</td>";
fDate += "<td>" + filterDate.start + "</td>";
fDate += "<td>" + filterDate.end + "</td>";
fDate += "</tr>";
});
fDate += "</table>";
document.getElementById("demo1").innerHTML = fDate;
}
<body onload="filterDates()">
<select id="endDate" onchange="filterDates(this.value);">
<option label="All Years" value="All">All Years</option>
<option label="Past Years" value="Past">Past Years</option>
<option label="Present" value="Present">Present</option>
</select>
<p id="demo1"></p>
<body/>
关键是过滤,我不想改变太多,所以我大部分时间都离开了如何做,除了现在它内部使用Array.filter和switch
来知道如何根据所选选项进行过滤。