日期:2014-05-16  浏览次数:20441 次

js中document.getElementById在IE出错在Firefox正确

Element_value = document.getElementById (ID_name )
参数:
ID_name:必选项 字符串(String)。
返回值:
Element_value: 获取对应ID名字 对象(Element)。
说明:
根据指定的id属性值得到对象。返回id属性值等于ID_name的第一个对象的

引用。假如对应的为一组对象,则返回该组对象中的第一个。
如果无符合条件的对象,则返回 null 。

它是一个document对象的方法,可以通过它来获得指定id的html元素。
例如在页面里表单元素你可以给它设置id值,或name值来区别同种类型的不同元素,当你设置id document.getElementById("id")来得到这个

元素,从而通过document.getElementById("id").value 得到元素的值,类似的方法还有document.getElementsByName("name")通过元素名称

来获得元素对象。document.getElementsByTagName("form")通过标签名称获得元素。

document.getElementById的一些细节
document.getElementById 有时会抓name放过了id ,据说是IE的一个BUG

———————————————————
<html>
<head>
<title>JS的document.getElementById的bug</title>
<script language="javascript">
?
?? function test()
?? {
??? var obj = document.getElementById('category_id');
??? alert(obj.value);
?? }
</script>
</head>
<body >

input的文本框的name="category_id" <br/>
select的下拉链的id="category_id" <br/>
用document.getElementById应该取得第二个,但是取到的却是第一个 <br/>

<input type="text" id="hello8" name="category_id" value="inputVal" />

<select id="category_id" onchange="al();">
??? <option value ="selectVal">下拉链</option>
</select>

<input type ="button" onclick="test()" value ="test">

</body>
</html>
———————————————————
name=category_id.在IE中getElementById竟然不是先抓id而是先找name

相同的物件...


两个form,每个form有两个textbox,两个form中的textbox是相同的name,

但id都不同...
這樣在Firefox是沒問題的...但在IE卻只抓得到第一个出現的name資料

下面这段代码可以验证这个结果
————————————————————
<html>
<head>
<title>document.getElementById在IE错误,Firefox正确</title>
</head>
<script language="JavaScript">
<!--
function chkacc(){
??? alert(document.getElementById("userId").value);//理论值:1 实际值: 1
??? alert(document.getElementById("passwordId").value); //理论值:2 实际值:2
??? alert(document.getElementById("userName").value); //理论值:A 实际值:1
??? alert(document.getElementById("password").value); //理论值:B 实际值:2
}
//-->
</script>

<body>
<h3>第一个Form表单</h3>
<form method="post" action="" name="frm1">
<input type="text" name="userName" id="userId" value="1"/>
<input type="text" name="password" id="passwordId" value="2"/>
</form>

<h3>第二个Form表单</h3>
<form method="post" action="" name="frm2">
<input type="text" NAME="userName" id="userName" value="A"/>
<input type="text" NAME="password" id="password" value="B"/>
<input type="button" value="检查" name="btnchk" onclick="chkacc();" />
</form>

</body>
</html>
————————————————————

② javascript中的getElementbyId使用
网页中的元素必须有id属性,才能通过这个方法得到,比如
<input type=text name="content" id="content">

③获取html标记主要有两种方法,一种是通过ID值,一种是通过name属性
name属性主要用于form表单内的input标记