背景
根据 WHATWG someForm.elements
应该返回 HTMLFormElementsCollection
.
HTMLFormElementsCollection
返回 RadioNodeList
如果多个元素共享相同的名称。
RadioNodeList
有特殊的 value
它返回节点列表中第一个检查的 radio 列表的值的语义。
这将允许 following answer to work if it were implemented
我naively attempted a polyfill这是基于表现良好的宿主对象(根据 WebIDL),而它们显然不是。
问题
在我们等待浏览器兼容 RadioNodeList 或 WebIDL 时,此 polyfill 的替代高效实现是什么?
示例引用代码
<form name="myform">
<input type="radio" name="foo" value="10" /> foo
<input type="radio" name="foo" value="30" /> bar
</form>
var myform = document.forms.myform;
var radio = myform.elements.foo;
var price = radio.value;
天真的尝试引用代码
(function () {
var pd = Object.getOwnPropertyDescriptor(HTMLFormElement.prototype, "elements"),
getElements = pd.get;
pd.get = get;
Object.defineProperty(HTMLFormElement.prototype, "elements", pd);
function get() {
var elements = getElements.call(this);
if (elements.length) {
Object.defineProperty(elements, "value", {
get: getRadioNodeListValue,
set: setRadioNodeListValue,
configurable: true
});
}
return elements;
}
function getRadioNodeListValue() {
for (var i = 0, len = this.length; i < len; i++) {
var el = this[i];
if (el.checked) {
return el.value;
}
}
}
function setRadioNodeListValue(value) {
for (var i = 0, len = this.length; i < len; i++) {
var el = this[i];
if (el.checked) {
el.value = value;
return;
}
}
}
}());
最佳答案
如果您可以接受将 value
getter 连接到 NodeList
上,那么以下应该可以工作
感谢@@Esailija
you could also just add .value to NodeList prototype
关于javascript - 如何填充 RadioNodeList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8941984/