[英]Select onchange reload the page and keep the selected option
我有这个https://jsfiddle.net/1zqgeq79/2/
这是我用来在更改选择时刷新页面的jquery,现在我只需要在页面加载后保留选定的选项。
$('.ProductDetails select').change(function () {
location.reload();
});
由于我有多个项目,我知道必须使用(这个),但我还在学习jquery。 谢谢您的帮助!
如果您不想在关闭浏览器后保持数据的持久性,请使用sessionStorage而不是localStorage。
我用以下代码替换了代码:
var selectedProduct = sessionStorage.getItem("product");
if(selectedProduct != undefined || selectedProduct != null){
$(".ProductDetails select").first().find(":selected").removeAttr("selected");
$(".ProductDetails select").find("option").each(function () {
if ($(this).val() == selectedProduct) {
$(this).attr("selected", true);
}
});
}
$('.ProductDetails select').change(function () {
sessionStorage.setItem("product", $(".ProductDetails select").first().val());
location.reload();
});
请访问: https : //jsfiddle.net/1zqgeq79/3/
我只做了第一次下拉。
当您重新加载页面时...所有脚本的运行方式与第一次加载时的运行方式相同。 以前的加载中没有保存或访问任何内容。
但是,您可以将数据存储在cookie或localStorage中,并在页面加载时访问该数据。
尝试类似的东西:
$(function(){
// get stored value or make it empty string if not available
var storedValue = localStorage.getItem('prod-detail') || '';
$('.ProductDetails select').change(function () {
// store current value
var currValue = $(this).val();
localStorage.setItem('prod-detail', currValue );
// now reload and all this code runs again
location.reload();
})
// set stored value when page loads
.val(storedValue)
});
更好的解决方案可能是使用ajax更新存储在服务器上的购物车,并在页面加载时设置所有存储的值
您可以在重新加载之前添加查询字符串参数。
var url = document.location;
document.location = url + "?select=" + $(this).val();
因此,当页面加载时,您可以读取此参数并按您的意愿操作。
您也可以使用cookie执行此操作。 jQuery允许你这样做。 看看这个链接: http : //plugins.jquery.com/cookie/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.