简体   繁体   中英

JQuery cookie set in other Function

I had a javascript Function showHide(shID) , which is a function to hide div or show content after clicked "read more" . Here is my Fiddle : http://jsfiddle.net/Garfrey/5xf72j4m/8/

As you see when user click on it and show more content , but I just need to hide once , means when the user come back to visit my page and the hidden content is still showing. So that I need to add JQuery cookie , but what I wrote was wrong and it's not working .I'am new in Javascript . Do anyone know how to fix it ? thanks in advance , I really need help .

here my code for function :

<script language="javascript" type="text/javascript">
jQuery(document).ready(function(){
   if($.cookie("example")=='1') {
      function showHide(shID) {
      if (document.getElementById(shID+'-show').style.display != 'none') {
         document.getElementById(shID+'-show').style.display = 'none';
         document.getElementById(shID).style.display = 'block';
      }
      else {
         document.getElementById(shID+'-show').style.display = 'inline';
         document.getElementById(shID).style.display = 'none';
      }
   }
   } else {

        $.cookie("example", "1");
    }                 
});

</script>

You can't define a function inside jQuery's ready function without doing something like this

 var showHide; $(function() { // Document ready showHide = function(sh) { //Insert function code here }; }); 

I think in your case you might be better off defining the function outside of the ready function then binding it to the button's onclick handler dynamically.

I also added a data-showhide attribute to the button to pass the variable into the showhide function onclick.

 function showHide() { var shID = $(this).data("showhide"); // Use lower case only in data if (document.getElementById(shID + '-show').style.display != 'none') { document.getElementById(shID + '-show').style.display = 'none'; document.getElementById(shID).style.display = 'block'; } else { document.getElementById(shID + '-show').style.display = 'inline'; document.getElementById(shID).style.display = 'none'; } } $(function() { $("#example-show").on("click", showHide); }); 
 <a href="#" id="example-show" class="showLink" data-showhide="example"> 

The cookies can be set to specific values in the showHide function. The ready handler can then query the cookie and determine whether or not to show or hide the div. This fiddle shows this in action http://jsfiddle.net/e52hxosb/19/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM