批量替换 select 中的选项 html 字符串?
我想“切换”选择框中的选项列表。
我有两组选项作为字符串(美国各州和加拿大各省)。但是,我注意到在 DOM 中,select
对象没有“innerhtml”属性(至少根据 w3schools 没有)。
我必须去把选项一一删除并替换吗?我该怎么做?
I would like to 'toggle' the list of options in a select box.
I have the two sets of options as strings (American states and Canadian Provinces). However, I notice that in the DOM, the select
object has no 'innerhtml' property (at least not according to w3schools).
Do I have to go and remove and replace the options one by one? How do I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
利用 jQuery,我通常会做这样的事情:
至于一对一的想法,请确保保留考虑到 DOM 交互普遍缓慢。整个字符串的批量替换将会非常快,但是如果您为
select
中的每个元素操作 DOM,那么预计它会很慢。Making use of jQuery, I usually do something like this:
As for the one-by-one idea, make sure you keep in mind the general slowness of DOM interaction. Wholesale replacement with the entire string is going to be pretty quick, but if you manipulate the DOM for each element in the
select
then expect it to be slow.我要做的就是创建两个,每个都在一个 DIV 中;然后隐藏不需要的那个。这消除了对大量 DOM 操作的需要(因为您只在页面加载时执行一次,因此在某些浏览器中泄漏内存的机会更少咳咳),并且更难意外搞砸应用程序状态(艾伯塔省和阿拉巴马州共享相同的代码等等)。
这将是初始页面:
以及随之而来的 JavaScript(为了简洁起见,此处使用了 jQuery):
结果应该是:
在后端,处理
state_usa
iffcountry
= ='美国';处理province_canada
当且仅当country
=='加拿大'。What I would do is create both, each in a DIV; then just hide whichever is not needed. This eliminates the need for heavy DOM manipulation (as you're only doing that once, on page load, there are fewer opportunities to leak memory in certain browsers cough cough), and is harder to accidentally mess up the app state (what with Alberta and Alabama sharing the same code and all that).
This would be the initial page:
and JavaScript to go with it (jQuery used here for brevity):
This should be the result:
At the backend, process
state_usa
iffcountry
=='USA'; processprovince_canada
iffcountry
=='Canada'.为什么不替换整个
包装在 SPAN/DIV 中并替换其innerHTML。
如果您要从数组中提取列表,则可以将列表长度设置为零,然后 在循环中插入新元素。
Why not replace the entire
<SELECT>
? There are a number of ways to do this. Easiest is to wrap the<SELECT>
in a SPAN/DIV and replace its innerHTML.If you're pulling your lists from an array, you can set the list length to zero, then insert the new elements in a loop.
当您说它们作为字符串保存时,您的意思是每个项目都是一个单独的字符串,还是列表项是一个字符串(即 var variable = "
";)
如果是后者,您是否可以不在字符串中包含
When you say they are held as strings - do you mean that each item is a seperate string or that the list items are one string (i.e. var variable = "
<li>item 1</li><li>item 2</li>
";)If the latter, could you not include the
<select>
tag in the string and use the jQuery replaceWith function?如果您想要进行多项选择,只需将
multiple="multiple"
属性添加到您的select
标记中,或者添加size=".."
即可单选Just add a
multiple="multiple"
attribute to yourselect
tag if you want multiple selection or addsize=".."
if you want single selection