【问题标题】:How to change a <select> element back to the default value when hitting the back button?点击后退按钮时如何将 <select> 元素更改回默认值?
【发布时间】:2014-05-10 03:16:12
【问题描述】:

我有一个&lt;select&gt; 元素,用于导航。您单击它以选择要转到的页面,然后单击它会转到该页面。这是它的代码:

<select onchange="window.open(this.options[this.selectedIndex].value,'_top')">
    <option value="/item1" selected>Item 1</option>
    <option value="/item2" selected>Item 2</option>
    <option value="/item3" selected>Item 3</option>
</select>

当我使用它时,它会正确进入页面,但是当点击后退按钮时,下拉菜单中已经选择了我去的页面。比如我在第 1 项,然后选择第 2 项,然后通过浏览器的返回按钮回到第 1 项,在列表中选择第 2 项,这有点混乱。

如何让它切换回默认值?

【问题讨论】:

  • 我认为浏览器的后退按钮会显示页面的缓存副本,并且 nat 实际上会重新加载页面。我想。

标签: html drop-down-menu default forms back-button


【解决方案1】:

您可以将选择框重置为默认值,然后导航到新页面。这是一个如何做到这一点的示例。

<script>
fix_ipad = function(evt){
    go_to = document.getElementById('go_to');
    go_to.selectedIndex = 0; // reset to default value before leaving current page
};

window.addEventListener("pagehide",fix_ipad,false);

goto_page_and_reset_default = function(){
    go_to = document.getElementById('go_to');
    go_to_page = go_to.value;
    go_to.selectedIndex = 0; // reset to default value before leaving current page

    window.open(go_to_page,"_top");    

}
</script>

<select onchange="goto_page_and_reset_default()" id='go_to'>
    <option value="/item1" selected>Item 1</option>
    <option value="/item2" selected>Item 2</option>
    <option value="/item3" selected>Item 3</option>
</select>

【讨论】:

  • 在 iPad 上,当我测试它时,它不起作用,但在 Windows 8 上它可以工作。有什么修复吗?
  • 我已经为 ipad 添加了一个可能的修复程序,但我无法对其进行测试。让我知道它是否适合您。
【解决方案2】:

可能重复https://stackoverflow.com/questions/8861181

现代浏览器实现了一种称为后向缓存 (BFCache) 的东西。当您点击后退/前进按钮时,实际页面不会重新加载(并且脚本永远不会重新运行)。

如果您必须在用户点击后退/前进键的情况下执行某些操作 - 侦听 BFCache pageshow 和 pagehide 事件。

一个伪 jQuery 示例:

$(window).bind("pageshow", function() {
  // update hidden input field
});

【讨论】:

  • 您能否在$(window).bind("pageshow") 函数中调用location.reload(); 以确保不会发生这种情况?
猜你喜欢
  • 1970-01-01
  • 2014-01-31
  • 1970-01-01
  • 2013-02-17
  • 1970-01-01
  • 1970-01-01
  • 2020-01-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多