【问题标题】:How do i change an element based on cookie value set in jQuery without reloading the page?如何在不重新加载页面的情况下根据 jQuery 中设置的 cookie 值更改元素?
【发布时间】:2021-09-10 17:46:13
【问题描述】:

好的,所以我对 jQuery 非常了解,我编写的代码无疑效率低下,但它在一定程度上有效。

我有一个表单,客户在其中选择“企业”或“个人”,并在提交时设置了一个 cookie...影响页面需要重新加载。如何在选择选项时触发此操作?

$(document).ready(function(){
$("#thankyoumessage").css("display","none");
            
    $(".storagetype").click(function(){
        if ($('input[name=customertype]:checked').val() == "Personal" ) {
            $("#thankyoumessage").slideDown("fast"); //Slide Down Effect
            $.cookie('customerIs', 'personal_cust', { path: '/', domain: 'storebox.co.uk'});   
if ("ga" in window) {
    tracker = ga.getAll()[0];
    if (tracker)
        tracker.send("event", "customer_type", "Personal");
};         
        } else if ($('input[name=customertype]:checked').val() == "Business" ) {
            $("#thankyoumessage").slideDown("fast"); //Slide Down Effect
            $.cookie('customerIs', 'business_cust', { path: '/', domain: 'storebox.co.uk'});   
if ("ga" in window) {
    tracker = ga.getAll()[0];
    if (tracker)
        tracker.send("event", "customer_type", "Business");
};          
        } else {
            $("#thankyoumessage").slideUp("fast");  //Slide Up Effect
        }
     });  
     
      var customerIs = $.cookie('customerIs');  
     
      if (customerIs == 'personal_cust' || customerIs == 'business_cust') {  
        
        $("#customerTypeForm").css("display","none"); 
        

      };
        
        var customerIs = $.cookie('customerIs');
if (customerIs == 'business_cust') {  
        
        $('li.unit:nth-of-type(1) .unit__img-wrap img').attr('src', 'https://www.storebox.co.uk/wp-content/uploads/2021/06/unit-small-trade.png');
        $('li.unit:nth-of-type(2) .unit__img-wrap img').attr('src', 'https://www.storebox.co.uk/wp-content/uploads/2021/06/unit-medium-trade.png');
        $('li.unit:nth-of-type(3) .unit__img-wrap img').attr('src', 'https://www.storebox.co.uk/wp-content/uploads/2021/06/unit-large-trade.png');
        

      };
          
});

提前致谢

【问题讨论】:

  • 您可以将代码末尾的“src”更改复制粘贴到“ else if ($('input[name=customertype]:checked').val() == “商业”)“
  • 感谢 Costa,唯一的问题是它会在选择选项时交换图像,但是它需要从 customerIs == 'business_cust' 值触发,以便图像切换在类似页面上持续存在或者如果他们重新访问该页面
  • 你不是说你让它在下次刷新时工作吗?这意味着保留这两个部分,一旦您第一次在页面上,它会与第一部分一起更改它,并且在接下来的所有时间中,它将根据 cookie 进行更改。嗯,我错了吗?
  • Doh....你说得对哈哈,谢谢哥们

标签: javascript jquery cookies dynamic


【解决方案1】:

回答我在 cmets 中的内容,以便您可以将问题标记为已解决;)

您可以复制粘贴您在结尾处所做的“src”更改 " else if ($('input[name=customertype]:checked').val() == "商业")"

保留这两个部分,当您第一次访问该页面时 用第一部分改变它,在接下来的所有时间里,它都会 根据 cookie 进行更改。

【讨论】:

    猜你喜欢
    • 2020-04-20
    • 1970-01-01
    • 2018-04-15
    • 2020-12-29
    • 2020-10-04
    • 1970-01-01
    • 1970-01-01
    • 2012-04-06
    相关资源
    最近更新 更多