Domanda

Perché NodeList non è definito in IE6 / 7?

<form action="/" method="post" id="testform">
    <input type="checkbox" name="foobar[]" value="1" id="" />
    <input type="checkbox" name="foobar[]" value="2" id="" />
    <input type="checkbox" name="foobar[]" value="3" id="" />    
</form>

<script type="text/javascript" charset="utf-8">
(function () {
    var el = document.getElementById('testform')['foobar[]']
    if (el instanceof NodeList) {
        alert("I'm a NodeList");
    }  
})();
</script>

Funziona in FF3 / Safari 3.1 ma non funziona in IE6 / 7. Qualcuno ha qualche idea su come verificare se el è un'istanza di NodeList su tutti i browser?

Nessuna soluzione corretta

Altri suggerimenti

" Duck Typing " dovrebbe sempre funzionare:

...

if (typeof el.length == 'number' 
    && typeof el.item == 'function'
    && typeof el.nextNode == 'function'
    && typeof el.reset == 'function')
{
    alert("I'm a NodeList");
}

La risposta di Adam Franco quasi funziona. Sfortunatamente, typeof el.item restituisce cose diverse in diverse versioni di IE (7: string, 8: object, 9: function). Quindi sto usando il suo codice, ma ho cambiato la riga in typeof el.item! == " undefined " e ho cambiato == in === ovunque.

if (typeof el.length === 'number' 
    && typeof el.item !== 'undefined'
    && typeof el.nextNode === 'function'
    && typeof el.reset === 'function')
{
    alert("I'm a NodeList");
}

Vorrei solo usare qualcosa che valuta sempre un certo tipo. Quindi fai un controllo di tipo vero / falso per vedere se hai un oggetto valido. Nel tuo caso, vorrei ottenere un riferimento all'elemento selezionato come sei ora e quindi utilizzare il suo metodo getOptions () per ottenere un HTMLCollection che rappresenta le opzioni. Questo tipo di oggetto è molto simile a un NodeList, quindi non dovresti avere problemi a lavorarci.

Con jQuery :

if (1 < $(el).length) {
    alert("I'm a NodeList");
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top