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

小问题求解
为什么这个getElementById不正确
JScript code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<script language="javascript">
function FileClick(){
    var Cl = event.srcElement.parentElement;
    var a = Cl.getElementById("aa");
    alert(a.tagName);
}
</script>
</head>

<body>
<form id="form1" name="form1" method="post" action="">
    <div>
      <input type="text" name="aa" id="aa" />
      <input type="button" name="button" id="button" value="点击" onclick="javascript:FileClick();" />
    </div>
    <div>
      <input type="text" name="aa" id="aa" />
      <input type="button" name="button" id="button" value="点击" onclick="javascript:FileClick();" />
    </div>
    <div>
      <input type="text" name="aa" id="aa" />
      <input type="button" name="button" id="button" value="点击" onclick="javascript:FileClick();" />
    </div>        
</form>
</body>
</html>



但是可以找到tagName
JScript code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<script language="javascript">
function FileClick(){
    var Cl = event.srcElement.parentElement;
    alert(Cl.tagName);
}
</script>
</head>

<body>
<form id="form1" name="form1" method="post" action="">
    <div>
      <input type="text" name="aa" id="aa" />
      <input type="button" name="button" id="button" value="点击" onclick="javascript:FileClick();" />
    </div>
    <div>
      <input type="text" name="aa" id="aa" />
      <input type="button" name="button" id="button" value="点击" onclick="javascript:FileClick();" />
    </div>
    <div>
      <input type="text" name="aa" id="aa" />
      <input type="button" name="button" id="button" value="点击" onclick="javascript:FileClick();" />
    </div>        
</form>
</body>
</html>



------解决方案--------------------
function FileClick(){
var Cl = event.srcElement.parentElement;
var a = Cl.getElementById("aa");
alert(a.tagName);
}

Cl在上下文中批按钮所在的<DIV>,而节点<div>没有getElementById方法
但是每个节点都有tagName属性,所以下面的可以正确的找到

可以使用childNodes属性来获取
function FileClick(){
var Cl = event.srcElement.parentElement;
alert(Cl.childNodes[0].tagName); //在IE中可以正确解析,不同的浏览器对空格的解析有点不一样
}