添加“选定”使用选项值的属性
我有一个包含 10 个选项的选择框。每次您选择一个选项时,它都会在本地存储中设置您使用 id“select1”选择的值。
例如:如果您选择本地存储中的第一个选项:键:Emailclient - 值:Option1。
现在,Iom 尝试将 localstorage 的值设置为 select 表单中的 selected 属性。
这是我尝试过的,但似乎不起作用:
if (localStorage.getItem("Select1") == "Option1"){
$('#selectbox').val("Option1").attr("selected");
}
我做错了什么?
编辑:
这是我的代码:
<select id="selectbox" >
<option>Default</option>
<option>Option 1</option>
<option>Option 3</option>
<option>Option 3</option>
<option>Option 4</option>
<option>Option 5</option>
<option>Option 6</option>
</select>
谢谢
I have a select box with 10 options. Each time you select an option it sets in the localstorage the value you selected with id "select1".
For example: If you select the first option you get in the localstorage: Key: Emailclient - Value: Option1.
Now, Iom trying to make the value of the localstorage, the selected attribute in the select form.
This is what I tried but doesn't seem to work:
if (localStorage.getItem("Select1") == "Option1"){
$('#selectbox').val("Option1").attr("selected");
}
What I'm I doing wrong?
EDIT:
This is my code:
<select id="selectbox" >
<option>Default</option>
<option>Option 1</option>
<option>Option 3</option>
<option>Option 3</option>
<option>Option 4</option>
<option>Option 5</option>
<option>Option 6</option>
</select>
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这有效:
This works:
我想你可能正在寻找这样的东西。 http://jsfiddle.net/tnPU8/3/
它循环选择框的选项并将它们的值与
b
的值进行比较。如果它们相等,则更改选择框的索引,以便显示包含b
值的选项。编辑:使用
localStorage
http://jsfiddle.net/tnPU8/7/I think you might be looking for something like this. http://jsfiddle.net/tnPU8/3/
It loops through the options of the select box and compares their values with the values of
b
. If they are equal the index of the select box is changed so that the option that contains the value ofb
is displayed.Edit: Using
localStorage
http://jsfiddle.net/tnPU8/7/试试这个:
如果您使用的 jQuery 版本早于 1.6,请将
.prop
替换为.attr
编辑:更动态的版本
Try this:
if you are using a version of jQuery older than 1.6, replace
.prop
with.attr
Edit: more dynamic version
经过进一步审查,您似乎想要一些功能更齐全的链接
On further review, it looks as though you wanted something more fully feature link
这就是您所需要的:
我已经更新了之前的小提琴示例:
http://jsfiddle.net/uY7ck/1/
编辑:
在您最初发布的代码中,假设您使用相同的选择框设置 localStorage,您将比较“Option1”(无空格)与“Option 1”(空格)。这种比较永远不会起作用,因此永远不会选择该选项。
This is all you should need:
I've updated a previous fiddle for an example:
http://jsfiddle.net/uY7ck/1/
EDIT:
In the code you posted originally, assuming you are setting localStorage with the same select box, you would be comparing "Option1" (no space) with "Option 1" (space). That comparison will never work, so the option would never be selected.