Sim*_*mon 0 javascript collections select
我有一个选择列表:
<select id="sel">
<option>text1</option>
<option>text2</option>
<option>text3</option>
<option>text4</option>
</select>
Run Code Online (Sandbox Code Playgroud)
我想删除所有项目,没有for
循环.我试过了:
document.getElementById('sel').length = 0;
Run Code Online (Sandbox Code Playgroud)
但这在某些浏览器中不起作用.
有任何想法吗?
谢谢
document.getElementById( 'sel' ).innerHTML = '';
Run Code Online (Sandbox Code Playgroud)
您应该将此类length
属性理解为更像是只读属性,该属性为您提供有关对象状态的信息.就像你得到一个数组的长度.但是,更改该值不会影响实际对象,而正确删除元素将导致浏览器重新呈现该元素的DOM(并因此更新该值).我想有些浏览器可能会将长度设置为零来解释清除该对象但通常不应该是预期的行为.另外我认为Element.length
实际上不是DOM规范的一部分.
要添加一些引用,核心DOM元素没有任何长度参数.两者HTMLSelectElement和HTMLOptionsCollection(其可以通过以下方式访问HTMLSelectElement.options
)具有长度属性,但将其设置应引起抛出:DOMException.
因此,在两种方式中,标准设置长度都是非法的,因此如果您想支持大多数浏览器,则不应使用它.