オブジェクトがIEのNodeListのインスタンスであるかどうかを確認する方法は?
-
02-07-2019 - |
質問
IE6 / 7ではNodeListが未定義なのはなぜですか
<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>
これはFF3 / Safari 3.1では機能しますが、IE6 / 7では機能しません。 elがすべてのブラウザーでNodeListのインスタンスであるかどうかを確認する方法はありますか?
正しい解決策はありません
他のヒント
&quot; ダックタイピング&quot;常に動作するはずです:
...
if (typeof el.length == 'number'
&& typeof el.item == 'function'
&& typeof el.nextNode == 'function'
&& typeof el.reset == 'function')
{
alert("I'm a NodeList");
}
アダムフランコの答えは、ほとんどほとんどうまくいきます。残念ながら、 typeof el.item
はIEのバージョンによって異なるものを返します(7:文字列、8:オブジェクト、9:関数)。そこで彼のコードを使用していますが、行を typeof el.item!==&quot; undefined&quot;
に変更し、 ==
を === <に変更しました/ code>全体。
if (typeof el.length === 'number'
&& typeof el.item !== 'undefined'
&& typeof el.nextNode === 'function'
&& typeof el.reset === 'function')
{
alert("I'm a NodeList");
}
常に特定のタイプに評価されるものを使用します。次に、true / false型チェックを実行して、有効なオブジェクトを取得したかどうかを確認します。あなたの場合、私はあなたと同じようにselectアイテムへの参照を取得し、そのgetOptions()メソッドを使用してオプションを表すHTMLCollectionを取得します。このオブジェクトタイプはNodeListに非常に似ているため、問題なく作業できます。
jQuery を使用:
if (1 < $(el).length) {
alert("I'm a NodeList");
}
所属していません StackOverflow