简体   繁体   中英

javascript doesn't work in web app

I'm developing an android app using phonegap. I created a favorite section on my app and I use localstorage to set a value of file name to 1 . Then I created a page named fav.html and I set the display value of my list to none like this :

 <ul class="table-view"> <li class="table-view-cell" style="display: none;"> <a class="navigate-left padder" href="modele1.html" data-transition="slide-in" >item1</a> </li> <li class="table-view-cell" style="display: none;"> <a class="navigate-left padder" href="modele2.html" data-transition="slide-in" >item2</a> </li> </ul> 
Than I used a javascript code like this to change the display value to block

 <script> if (localStorage.getItem("modele1.html")==1){document.getElementsByClassName("table-view-cell")[0].style.display = 'block';} if (localStorage.getItem("modele2.html")==1){document.getElementsByClassName("table-view-cell")[1].style.display = 'block';} </script> 

I already checked and localstorage value for modele1.html and modele2.html is set to 1 . The code works fine on chrome but when I build the code with phonegap the script doesn't work. I even added the script manually to my end of fav.html before the </body> tag and rebuild the app but it still doesn't work on the phone? Please help me this is important.

I'm not totally sure, but one thing that occurred to me was that you aren't waiting for deviceready event. This might be required for Cordova but not for Chrome since Cordova needs to load the implementation during boot and Chrome already has it available. Try this

<script>
document.addEventListener("deviceready", function () {
    // alert("deviceready event");
    if (localStorage.getItem("modele1.html")==1) {
        // alert("1");
        document.getElementsByClassName("table-view-cell")[0].style.display = 'block';
    }
    if (localStorage.getItem("modele2.html")==1){
        // alert("2");
        document.getElementsByClassName("table-view-cell")[1].style.display = 'block';
    }
}, false);
</script>

If it still doesn't work as you intended, you can uncomment the alerts to see if the execution reaches there.

well finally i found the problem. i use fileName = location.pathname.substring(1); code to store the key of localstorage value. in windows the full address of file was /modele1.html so this code return file name but in phonegap the full address of file was /android_assets/www/modele1.html . so obviously i needed to change the code to fileName = location.pathname.substring(19); and Vola problem solved :)

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