Come polinodelista in polyfill?
-
06-11-2019 - |
Domanda
Sfondo
Secondo il Whatwg someForm.elements
dovrebbe restituire a HTMLFormElementsCollection
.
UN HTMLFormElementsCollection
Restituisce a RadioNodeList
Se più elementi condividono lo stesso nome.
Il RadioNodeList
ha speciale value
semantica in cui restituisce il valore del primo elenco radio controllato nel nodelist.
Questo consentirebbe il seguendo la risposta al lavoro se è stato implementato
io tentato ingenuamente un polyfill Questo si basa sugli oggetti host che si comportano bene (secondo WebIDL), che chiaramente non sono.
Domanda
Che cos'è un'implementazione efficiente alternativa per questo polyfill mentre aspettiamo che i browser diventino conformi a radionodelista o WebIDL?
Codice di riferimento di esempio
<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;
Codice di riferimento del tentativo ingenuo
(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;
}
}
}
}());
Nessuna soluzione corretta
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow