【发布时间】:2018-03-13 23:50:28
【问题描述】:
我有一组对象使用数据过滤器进行搜索和过滤。 JavaScript 切换对象的可见性以进行搜索和过滤。
我有一些标题元素应该只在选择它们的主题时出现。例如,如果用户选择主题#3,则主题#3 的结果应该与主题#3 的标题一起显示。如果我执行搜索,标题应显示“搜索结果”。
我迷路的地方:画廊从所有对象和部分标题开始。部分标题应隐藏,直到其部分主题被选中。我对所有可见元素都有“过滤器”类。如果我以可见性开始它们:隐藏;他们从不出现。如果我不给他们可见性:隐藏;他们永远不会离开。当我需要独立于主过滤来切换这些单个元素时,我的功能会显示和隐藏“全部”。
这是一个小提琴,显示页面加载时的所有标题,以及当您键入或单击“全部”时。在这些情况下显示的唯一标题应该是“所有结果”。
https://jsfiddle.net/ewebster/Lxveeq65/43/
JavaScript:
$(document).ready(function () {
//declare a global variable
var filterVal;
//check if sessionStorage exists and if so, if there is a var called fillTerm
//if not, set it to a default value (all)
if (sessionStorage && sessionStorage.getItem("filTerm")) {
filterVal = sessionStorage.getItem("filTerm");
} else {
filterVal = "all";
sessionStorage.setItem("filTerm", filterVal);
}
//now let's attach some interaction to our buttons
$(".filter-button").on("click", function () {
//get the value for our filter
filterVal = $(this).attr("data-filter");
//store it in the session storage
sessionStorage.setItem("filTerm", filterVal);
console.log(sessionStorage);
console.log(filterVal);
//call our view update function
updateView();
});
$("#searchBtn").on("click",function(){
filterVal = $('#searchEntry').val();
sessionStorage.setItem("filTerm", filterVal);
updateView();
});
$("#searchEntry").on("keypress",function(e){
if (e.keyCode == 13) {
filterVal = $('#searchEntry').val();
sessionStorage.setItem("filTerm", filterVal);
updateView();
}
});
//this is the function that manipulates the UI
function updateView() {
//default situation: all is visible
if (!filterVal || filterVal === "all") {
$('.filter').show();
}
//hide all and show filtered values
else {
$(".filter").hide();
$('.filter').filter('.' + filterVal).show();
console.log("searchTerm");
console.log("filterVal");
}
};
//update the view when the page loads
updateView();
});
【问题讨论】:
-
我建议不要使用“.hidden”css 类。而是隐藏 document.ready 中的所有图块,然后在每次单击按钮时显示它们。 jsfiddle.net/Lxveeq65/46
-
这样对最终用户会有一个闪烁。
-
感谢大家的辛勤工作和帮助。 Oluwafemi Sule 先把我整理出来。我保证将来会遇到更多的编程问题。
标签: javascript jquery css filter visibility