2017-04-17 145 views

回答

1

使用的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/

我做了唯一的第一个下拉。

+0

这工作完全谢谢你!有没有办法在JS运行时隐藏它,然后在完成时显示它? – xohbrittx

+0

隐藏下拉菜单中的完整下拉菜单或显示值为空? –

+0

我调整了代码,我用这个替换了代码: 隐藏下拉列表中的完整下拉列表或显示值为空? 我还想让你做POC,我通过删除代码来调整代码: $(“。ProductDetails select”)。find(“option”)。each(function(){ if($ (this).val()== selectedProduct){ $(this).attr(“selected”,true); } }); 并放置 $(“。ProductDetails select”)。val(selectedProduct) 如果您能够提交表单,请尝试。 –

0

您可以在重新加载之前添加查询字符串参数。

var url = document.location; 
document.location = url + "?select=" + $(this).val(); 

所以,当页面加载时,你可以阅读这个参数,并按你的意愿行事。

您也可以使用cookie来做到这一点。 jQuery允许你这样做。看看这个链接:http://plugins.jquery.com/cookie/

+0

*“你可以阅读这个参数”* ...怎么样?答案不完整 – charlietfl

+0

我不知道你在使用哪种语言?如果您只使用Javascript和HTML,则可以使用JS读取参数。看看这篇文章:http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript。 然后您可以这样做: '$('。ProductDetails select option [value =''+ val +'“]')。attr('selected','selected');' –

2

当你重新加载页面时...所有脚本的运行方式与第一次加载时相同。以前的加载没有保存或访问。

然而,您可以将数据存储在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来更新您的购物车存放在服务器上,并设置所有存储的值存在时,页面加载

+0

True,但用户将不得不去购物车看到其他UOM的价格,大多数人希望在将其添加到购物车之前查看所有选项的价格。 – xohbrittx

+0

不是我的意思...可以在页面中更新...但同时做页面重新加载的服务器端更新。有很多方法可以有一辆车 – charlietfl

相关问题