<SCRIPT> function fnGetId(){ // Returns the first DIV element in the collection. var oVDiv=document.getElementById("oDiv"); alert(oVDiv==null); } </SCRIPT> <DIV ID="oDiv">Div #1</DIV> <DIV ID="oDiv">Div #2</DIV> <DIV ID="oDiv">Div #3</DIV> <INPUT TYPE="button" VALUE="Get Names" onclick="fnGetId()">
<SCRIPT> function fnGetNames(){ // Returns a collection with 2 INPUT type=text elements. var aInput=document.getElementsByName("firstName"); if(aInput==null) alert("Object not exist"); else alert("Object Exists");} </SCRIPT> <INPUT TYPE="text" NAME="firstName"> <INPUT TYPE="text" NAME="firstName"> <INPUT TYPE="button" VALUE="Get Names" onclick="fnGetNames()">
<SCRIPT> function fnGetId(){ // Returns the first DIV element in the collection. var oVDiv=document.getElementById("oDiv"); if(oVDiv==null) alert("Object not exist"); else alert("Object Exists"); } </SCRIPT> <DIV ID="oDiv">Div #1</DIV> <DIV ID="oDiv">Div #2</DIV> <DIV ID="oDiv">Div #3</DIV> <INPUT TYPE="button" VALUE="Get Names" onclick="fnGetId()">
function fnGetId(){
// Returns the first DIV element in the collection.
var oVDiv=document.getElementById("oDiv");
alert(oVDiv==null);
}
</SCRIPT>
<DIV ID="oDiv">Div #1</DIV>
<DIV ID="oDiv">Div #2</DIV>
<DIV ID="oDiv">Div #3</DIV>
<INPUT TYPE="button" VALUE="Get Names" onclick="fnGetId()">
function fnGetNames(){
// Returns a collection with 2 INPUT type=text elements.
var aInput=document.getElementsByName("firstName");
if(aInput==null) alert("Object not exist");
else alert("Object Exists");}
</SCRIPT>
<INPUT TYPE="text" NAME="firstName">
<INPUT TYPE="text" NAME="firstName">
<INPUT TYPE="button" VALUE="Get Names" onclick="fnGetNames()">
function fnGetId(){
// Returns the first DIV element in the collection.
var oVDiv=document.getElementById("oDiv");
if(oVDiv==null) alert("Object not exist");
else alert("Object Exists");
}
</SCRIPT>
<DIV ID="oDiv">Div #1</DIV>
<DIV ID="oDiv">Div #2</DIV>
<DIV ID="oDiv">Div #3</DIV>
<INPUT TYPE="button" VALUE="Get Names" onclick="fnGetId()">
很多方法想起来能够行得通,比如上面的typeof,而实际上仔细想一下过程就会发现有问题,因为脚本的执行包含有两个方面的内容:
1.IE的DOM
2.脚本自身
typeof(o)首先需要IE通过DOM取出o,然后送给脚本进行类型判断,如果事先并不知道o是否存在,则在第一步IE就会报错,说找不到对象o,类似的错误还会发生在
if(document.all.b1)alert('该控件存在')
这类语句上。而getElementById是DOM提供的方法,它的对象ID是以字符串方式存在的,因此可以正确执行.
...
if ( typeof(o) == 'object' )
...