javascript 刷新后保持选中的选项(表单/选择)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13183764/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 18:01:04  来源:igfitidea点击:

Keep selected option (form/select) after refresh

phpjavascriptjquerysmarty

提问by Diego Sarmiento

Possible Duplicate:
Html select option lost data after submit

可能重复:
提交后 Html 选择选项丢失数据

I have a select menu that should keep the selected option after the page refresh. This is the example:

我有一个选择菜单,它应该在页面刷新后保留选定的选项。这是示例:

<select id="form_frame" name="frame" onchange="getData(this);"/>
   <option value="data1" selected="selected">Data 1</option>
   <option value="data2">Data 2</option>
</select>

Function getData just pull info to the user.

函数 getData 只是向用户拉取信息。

I'm using Smarty/php for the dynamic content.

我将 Smarty/php 用于动态内容。

Open to advice, thanks!

开放咨询,谢谢!

回答by adeneo

How it's done with local storage :

如何使用本地存储完成:

$(function() {
    if (localStorage.getItem('form_frame')) {
        $("#form_frame option").eq(localStorage.getItem('form_frame')).prop('selected', true);
    }

    $("#form_frame").on('change', function() {
        localStorage.setItem('form_frame', $('option:selected', this).index());
    });
});

FIDDLE

小提琴

回答by slash28cu

Put the id or value of the selected option element in your php session( $_SESSION['selected_option_id']), In this way this value is passed through all the pages. And then change on the code that generates the option elements check agains $_SESSION['selected_option_id']and if it matches one then set the selected attribute in the option element.

将所选选项元素的 id 或值放在您的 php session( $_SESSION['selected_option_id']) 中,这样该值就会通过所有页面传递。然后更改生成选项元素的代码,再次检查$_SESSION['selected_option_id'],如果匹配,则在选项元素中设置 selected 属性。

Sessions is a good way to share values between requests since HTTP is a stateless protocol.

会话是在请求之间共享值的好方法,因为 HTTP 是无状态协议。

I prefer session before localStorage and cookies because those ones may not be available or enabled in the clients browser. The session is a feature of apache/php and are supported on the servers side.

在 localStorage 和 cookie 之前,我更喜欢 session,因为这些可能在客户端浏览器中不可用或未启用。会话是 apache/php 的一个特性,在服务器端支持。

PHP Session Handling

PHP 会话处理

回答by Rob

You can use Cookies. However, if you want it to work it for users that won't accept cookies from your site, append the url with a hash-tag. Onchange of the select field you update the hash-tag. Onload of the page, you check for a present hash-tag and set the select to the option whose value matches the one of the hash-tag.

您可以使用 Cookie。但是,如果您希望它适用于不接受来自您网站的 cookie 的用户,请在 url 后附加一个哈希标签。选择字段的更改更新哈希标签。在页面加载时,您检查当前的散列标签并将选择设置为其值与散列标签之一匹配的选项。