如何将选择框的内容存储到变量中?
我的 HTML 页面上有一个
如何将选择字段的选项存储到变量中,然后再次将其加载到选择中?在某些情况下,能够恢复选择字段的默认选项会很有帮助。
I have a <select>
field on my HTML page that is populated with a few options. With the help of AJAX, I replace those options in the select field with more appropriate options.
How can I store the options of my select field into a variable and then load it into the select again? It would be helpful to be able to get back the default options of the select field in some cases.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我在这里使用了 jQuery 的
.children()
来保持它更多一点如果您使用元素,则为通用。
当需要恢复到原始内容时,您可以执行以下操作:
这会清空
I used jQuery's
.children()
here to keep it a little more generic in case you're using<optgroup>
elements.When it comes time to revert to the originals, you could do something like this:
This empties the
<select>
of its current content, and appends a clone of the defaults so that your copy is retained in its original state.如果您想恢复对象而不是 html() 字符串,可以使用 detach()
如何将其与
replaceWith()
一起使用的示例:http://jsfiddle.net/doktormolle/Sgn72/
If you want to restore the objects instead of the html()-string, you can use detach()
An example how to use it with
replaceWith()
:http://jsfiddle.net/doktormolle/Sgn72/
我的方法是使用 jQuery 的 .data 函数来存储选项 html。
回复:
当然这些都是基本的想法,我不太清楚你的逻辑是怎样的。 (如果我错了,请纠正我)。
My way would be using the jQuery's .data function to store the options html.
To resotre:
Of course these are the basic ideas, as I don't really know how's your logic. (And please correct me if I'm wrong).