document.getElementById('').length = 0 在 Win7 下不起作用
我有一个选择列表:
<select id="sel">
<option>text1</option>
<option>text2</option>
<option>text3</option>
<option>text4</option>
</select>
我想删除所有项目,而不使用 for
循环。 我尝试过:
document.getElementById('sel').length = 0;
但这在某些浏览器中不起作用。
有什么想法吗?
谢谢
I have a select list:
<select id="sel">
<option>text1</option>
<option>text2</option>
<option>text3</option>
<option>text4</option>
</select>
I want to delete all items, without for
loop.
I tried:
document.getElementById('sel').length = 0;
But this doesn't work in some browsers.
Any ideas?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
摘自评论:
您应该将这样的
length
属性理解为更像一个只读属性,它为您提供有关对象状态的信息。就像当你获取数组的长度时一样。然而,更改该值不会影响实际对象,而正确删除元素将导致浏览器重新渲染该元素的 DOM(并因此更新值)。我想某些浏览器可能会解释将长度设置为零将清除该对象,但一般来说这不应该是预期的行为。另外我认为Element.length
实际上不是 DOM 规范的一部分。要添加一些参考,核心 DOM 元素 没有任何长度参数。 HTMLSelectElement< /a> 和 HTMLOptionsCollection (可以通过
HTMLSelectElement.options
访问)具有长度属性,但设置它应该引发DOMException。因此,根据标准,这两种方式设置长度都是非法的,因此如果您想支持大多数浏览器,则不应使用。
Moved from comment:
You should understand such a
length
property more like a read-only property that gives you information about the state of the object. Like when you get the length of an array. Changing that value however doesn't affect the actual object, while removing an element correctly will cause the browser to re-render the DOM for that element (and as such update the value). I guess some browsers might interpret setting a length to zero will clear that object but in general that shouldn't be the expected behaviour. Also I thinkElement.length
actually isn't part of the DOM specification.To add some references to that, the core DOM Element doesn't have any length parameter. Both the HTMLSelectElement and the HTMLOptionsCollection (which can be accessed via
HTMLSelectElement.options
) have a length attribute but setting it should raise a DOMException.So in both ways setting the length is illegal by the standard and as such should not be used if you want to support most browsers.
这些工作之一:
或
Either of these work:
or