简体   繁体   中英

Set sessionStorage, change image

I just wish that based on the sessionstorage I set, the image would change ... sessionstorage is set correctly, but the image will not change...

what did I miss?

 function caption_on_off() { if(sessionStorage.getItem("caption_on_off") == 'off'){ sessionStorage.setItem("caption_on_off", 'on'); }else{ sessionStorage.setItem("caption_on_off", 'off'); } } function change_caption_img(){ if(sessionStorage.getItem("caption_on_off") == 'off'){ document.getElementById('caption_on_off_img').src = 'images/on.png'; }else{ document.getElementById('caption_on_off_img').src = 'images/off.png'; } } change_caption_img();
 <div id="gallery_div_caption" onclick="Hide('gallery_div_caption'); caption_on_off();"><img id="caption_on_off_img" src="images/off.png"></div>

I thought of doing it separately because the page is a php page, and is reloaded with new variables, new mysql queries etc., but I need the page to remember which image it should load based on the sessionstorage status even after being reloaded.

If it was all php I would save in a coockie and read it in php, can I read a sessionstorage via php?

---------------------update----------------------

I was thinking of adding a variable to my ajax url as suggested by M1K1O, maybe the simplest way, but it's a mess because it is compiled via php and then added to the html text, using all possible quotes... how do I add it now sessionstorage here?

$link_onclick .= "javascript:AjaxPhp('img_div', 'gallery_img.php', '?img_title=".clean_url($row_news['id_news']."-".$row_news['titolo'])."&amp;img_title_it=".clean_url($row_news['id_news']."-".$row_news['titolo_it'])."&amp;img_n=".$g."&amp;refer=".$row_news['refer']."&amp;link_out=".$link_out."&amp;captions_exist=".$captions_exist."&amp;caption_on_off= ... session storage here...'); Show('gallery_div'); return(false);";

I think your function and logic is fine but it is getting called only once with your syntax. Either wrap it in document ready or document load or I would suggest using IIFE, if you want your function to be called in every page reload as follows:

(function change_caption_img(){
    if(sessionStorage.getItem("caption_on_off") == 'off'){
        document.getElementById('caption_on_off_img').src = 'images/on.png';
    }else{
        document.getElementById('caption_on_off_img').src = 'images/off.png';
    }
})();

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