简体   繁体   中英

Resetting a select box not working on iPad, but works on Chrome on Windows

Here's the Javascript code I'm using right now.

$(document).ready(function(){
    $('#altNav').change(function(){
        var altNavSelectedVal = $('#altNav').val();
        if (altNavSelectedVal != 'currentPage')
        {
            $('#altNav option[value="currentPage"]').attr('selected', 'selected');
            location.href = altNavSelectedVal;
        }
    });
});

It's used to reset a select box with the ID altNav to the option with the value currentPage before navigating to the next page.

This is to prevent the browser from caching its previous value. For example, if I'm on the About page and I change it to Services, it will take me to the Services page. If I hit the browser back button it will go back to the About page but will have its active selection be Services, since it was changed to services just before it changed the page.

The HTML code is below.

<select id="altNav">
    <option value="/">Home</option>
    <option value="/services">Services</option>
    <option value="currentPage" selected="selected">Contact</option>
    <option value="/about">About</option>
    <option value="/news">News</option>
</select>

Normally the Contact option would have a value of /contact if it was on another page, but it's different for each page. The normal values are / for Home, /services , /contact , /about , and /news , but when it's on one of those page, that option's value is set to currentPage .

Anyway, the code works as it's supposed to on Chrome for Windows, but when I test on iPad (and probably iPhone), when hitting the back button it always returns to Home.

When I comment out the line location.href = altNavSelectedVal; it should, if I for example am on the News page and select Services, switch back to News after I select Services, but it actually selects Home. I don't understand why it would only do this on iOS.

I don't have an ipad/iphone but you may need to remove the old selected with

$('#altNav').removeAttr('selected');

http://jsfiddle.net/un45t/

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