页面加载后在javascript中存储值?

时间:2016-09-27 17:36:54

标签: javascript jquery html css cookies



$("#divid1").click(function(){
    $("#divid1").hide(); //want this to keep hidden after refresh
    $("#hideid1").hide(); //want this to keep hidden after refresh
    $("#id1").show(); //want this to keep showing after refresh
});

.hide{
    display:none; 
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="/img/done.png"  id="divid1" alt="divid1"/>
<img src="/img/schedule.png" height="12" width="12" id="hideid1" alt="hideid1" />
<div id="id1" class="hide"><img src="/img/done.png" height="12" width="12" alt="id1" /></div>
&#13;
&#13;
&#13;

我试图在页面加载后显示图像,当onclick();显示新图像并隐藏旧图像。 但是,在页面刷新时它会重置。

请给我一个解决方法。

使用我的ID的工作代码将不胜感激!!

4 个答案:

答案 0 :(得分:1)

尝试localStorage

设置项目

localStorage.setItem('selectedId', 100);

获取商品

localStorage.getItem('selectedId');

最后,删除项目

localStorage.removeItem("selectedId");

示例

$(document).ready(function(){
    //Function for events
    function dummyFunction(){
        $("#divid1").hide(); //want this to keep hidden after refresh
        $("#hideid1").hide(); //want this to keep hidden after refresh
        $("#id1").show(); //want this to keep showing after refresh
    }
    //Check localStorage value
    if(localStorage.setItem('itemClicked') == 1)
    {
       dummyFunction();
    }
    //Div click event
    $("#divid1").click(function(){
        dummyFunction();
        //Set localStorage
        localStorage.setItem('itemClicked', 1);
    });
});

答案 1 :(得分:0)

查看Example。这应该足够清楚。

JS

$("#divid1").click(function(){
   $("#divid1").hide(); //want this to keep hidden after refresh
   $("#hideid1").hide(); //want this to keep hidden after refresh
   $("#id1").show(); //want this to keep showing after refresh
   localStorage.setItem('hidden', true);
});

$(function() {
   // if localStorage has hidden as true, hide the div and show other
   if(localStorage.getItem('hidden')){
     $("#divid1").hide(); 
     $("#hideid1").hide(); 
     $("#id1").show();
   }
});

答案 2 :(得分:-1)

您可以使用Cookie来调用,就像用户点击页面加载一样。

除此之外,你还有点运气。页面刷新旨在重置页面的javascript。

答案 3 :(得分:-1)

我希望以下代码能为您提供帮助。只需将代码放入load事件并解决问题。

&#13;
&#13;
$(window).load(function(){
    $("#divid1").hide(); 
    $("#hideid1").hide();
    $("#id1").show(); 
});
&#13;
.hide{
    display:none; 
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="/img/done.png"  id="divid1" alt="divid1"/>
<img src="/img/schedule.png" height="12" width="12" id="hideid1" alt="hideid1" />
<div id="id1" class="hide"><img src="/img/done.png" height="12" width="12" alt="id1" /></div>
&#13;
&#13;
&#13;