最佳实践:访问单选按钮组
寻找最好的、符合标准的、跨浏览器兼容的、向前兼容的方式来访问 DOM 中的一组单选按钮(这与我最近的另一篇文章密切相关......),而不使用任何外部库。
<input type="radio" value="1" name="myRadios" />One<br />
<input type="radio" value="2" name="myRadios" />Two<br />
我读过有关 getElementsByName() 的冲突信息,这似乎是执行此操作的正确方法,但我不清楚这是否是符合标准、向前兼容的解决方案。也许有更好的方法?
Looking for the best, standards compliant, cross browser compatible, forwards compatible way to access a group of radio buttons in the DOM (this is closely related to my other most recent post...), without the use of any external libraries.
<input type="radio" value="1" name="myRadios" />One<br />
<input type="radio" value="2" name="myRadios" />Two<br />
I've read conflicting information on getElementsByName(), which seems like the proper way to do this, but I'm unclear if this is a standards compliant, forwards compatible solution. Perhaps there is a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我对这个解决方案并不完全满意,但我最终在 Gecko DOM 文档中找到了这个解决方案。
name 获取或设置 DOM 对象的 name 属性,它仅适用于以下元素:anchor、applet、form、frame、iframe、image、input、map、meta、object、option、param、select 和 textarea .
更多内容:https://developer.mozilla.org/en/ DOM/element.name
所以我认为这是一种符合标准的处理方式(尽管最佳实践可能并不存在......)
I'm not totally happy with this solution, but I did finally track this down in the Gecko DOM documentation.
name gets or sets the name attribute of an DOM object, it only applies to the following elements: anchor, applet, form, frame, iframe, image, input, map, meta, object, option, param, select and textarea.
More here: https://developer.mozilla.org/en/DOM/element.name
So I suppose this is a standards compliant way of proceeding (though a best practice may not really exist...)
我认为未来最好的事情是:
vs
原因是根据最新的 spec< /a>,
elements.someName
将返回一个RadioNodeList
对象(如果多个元素具有相同的名称),其中包含一个value
属性,指示检查项目的价值。另一方面,
form.myradios
将返回NodeList
的对象,它只是项目的有序集合,并且没有任何value
属性。传统上,在单选按钮和复选框中查找选中的项目是一项非常痛苦的工作。
但是,我不确定我们如何访问复选框的所有选中元素。在规范中找不到这个。希望没有遗漏。
I think the best thing going forwards is:
vs
The reason being that according to the latest spec,
elements.someName
will return an object ofRadioNodeList
(if multiple elements have the same name) that contains avalue
attribute indicating the checked item's value.form.myradios
on the other hand will return an object ofNodeList
which is just an ordered collection of items, and does not have anyvalue
property.Finding the checked items in radios and checkboxes has traditionally been a very painful exercise.
However, I am not sure how would we access all checked elements for checkboxes. Couldn't find that in the spec. Hope that is not missing.