开发者

Is there a faster way to empty a HTML Select box?

开发者 https://www.devze.com 2023-03-14 11:01 出处:网络
I have an HTML Select box with about 1800+ options.In my javascript I have the following line to empty the select box so I can repopulate it.

I have an HTML Select box with about 1800+ options. In my javascript I have the following line to empty the select box so I can repopulate it.

box.options.length = 0; 

In Firefox this runs fairly quickly, but IE takes a couple of seconds. 开发者_如何学运维Is there a faster way to do this in IE?


At some point I have worked around IE's dismal performance in this area by enclosing list object in a div and then when I needed to reset it I would just set innerHTML of that div to a brand new empty list html tag. I'm sketchy on the details but I think that's what I did and it worked.
Please don't tell anybody I suggested this to you.


One way that should be faster is to create a new select box with the same properties (but no options, of course), and replace the existing box with it.


You could use box.innerHTML="". In my test, it is 68% faster:

http://jsperf.com/emptying-a-select-box/4.

Update: in 2015 box.innerHTML = "" is by multiple orders of magnitude the slowest option. :-) Use box.options.length = 0 instead.

0

精彩评论

暂无评论...
验证码 换一张
取 消