function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}
谢谢!

解决方案 »

  1.   

    一个简单的dom查询器,返回的是一个dom元素
    参数:
    n:是查询字符串
    d:是dom元素
      

  2.   

    通过document.getElementById(n),返回对象,
      

  3.   

    正如4L所说,是通过document.getElementById(n),返回对象
    该对象可以在页面body中,也可以在iframe、form中
    MM_findObj(n, d)
    //n:对象ID,如果在iframe中,要用objectId?iframeId的格式
    //d:document对象,可以为空,也可以精确到具体的document、form等等a.htm<html><head>
    <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
    <title>a.htm</title>
    <script language="javascript" type="text/javascript" defer> 
    function MM_findObj(n, d) { //v4.01
        var p,i,x; 
        if(!d) d=document;
        if((p=n.indexOf("?"))>0&&parent.frames.length) {
            d=parent.frames[n.substring(p+1)].document; 
            n=n.substring(0,p);
        }
        if(!(x=d[n])&&d.all) x=d.all[n]; 
        for(i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
        for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
        if(!x && d.getElementById) x=d.getElementById(n); return x;
    }function $(id){
    return document.getElementById(id);
    }alert(MM_findObj("tr1",$("form1")).outerHTML);//tr1try{
    alert(MM_findObj("tr2",$("form1")).outerHTML);//报错
    }catch(exception){
    alert("找不到tr2");
    }alert(MM_findObj("div1?f1").outerHTML);//iframe中的div1alert(MM_findObj("div1",document.frames["f1"].document).outerHTML);//iframe中的div1</script>
    </head><body>
    <form id=form1 name=form1>
    <table id="tb1"> 
    <tr id="tr1"> </tr> 
    </table>
    </form><iframe name=f1 id=f1 src="b.htm"></iframe><table id="tb2"> 
    <tr id="tr2"> </tr> 
    </table>
    </body></html>
    b.htm
    <html><head>
    <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
    <title>b.htm</title>
    </head><body>
    <div id=div1>1111</div>
    </body></html>