我有一个过滤图库项目的过滤按钮列表。 过滤效果很好,过滤状态保存在 session 存储中。 我正在尝试链接搜索框和按钮。
我试图实现的行为是,当有人在搜索框中输入内容然后按回车键或单击搜索按钮时,他们的输入将传递给过滤函数并显示匹配结果。
我在获取字符串并将其分配给变量时遇到问题。 我无法让过滤器处理该变量。
我做了一个 fiddle 来演示: https://jsfiddle.net/ewebster/Lxveeq65/22/
JS:
$(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();
});
//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();
$(".searchButton").click(function () {
var term = $(this).attr('data-filter');
var searchTerm = document.getElementById("searchEntry").value;
console.log("searchTerm");
console.log("filterTerm");
})
});
最后的 searchButton 函数不起作用。我意识到按钮可以在点击时触发功能,或者功能可以监听按钮 ID 的点击。无论如何,我无法获取搜索输入。
表单可能需要 POST 方法,这取决于我问的地方。
最佳答案
当您单击该按钮时,将提交表单并重新加载页面。如果您可以在本地呈现所有表单,则无需使用表单。
我已经更新了 fiddle 以删除表单,并添加了一个新的点击处理程序。您可以添加另一个事件监听器来处理回车键并执行相同的操作。
我无法根据您的问题确定您是否需要发布表单。在我看来,他们只是在寻找客户端,因此我的回答放弃了表格。
https://jsfiddle.net/Lxveeq65/39/
$("#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();
}
});
关于javascript - 获取搜索框以过滤结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46498308/