function getClickElement(obj)
{
var pnode=obj;
var i=0;
for (i=0;i<10;i++)
{
pnode=pnode.parentNode;
document.write(pnode.nodeName+"<BR/>");
}
}这段代码我想获得选中节点的所有父节点,并且把他们的名字打印出来...
但是打印结果是只能显示第一个父节点...其他的父节点无法正常显示...我是js初学者,网上也没查到相关资料,不知道csdn的高手们能不能指导一二?

解决方案 »

  1.   

    没有问题<!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=utf-8" />
    <title>Untitled Document</title>
    </head><body>
    <div>
    <span>
         <div>
             <span id='a';>
                 a
                </span>
            </div>
        </span>
    </div>
    <script>
    function getClickElement(obj)
    {
    var pnode=obj;
    var i=0;
    for (i=0;i<10;i++)
    {
    pnode=pnode.parentNode;
    document.write(pnode.nodeName+"<BR/>");
    }
    }getClickElement(document.getElementById('a'));
    </script></body>
    </html>
      

  2.   

    那就说明只有一个父节点。要贴就贴全,这个和你调用的参数也有关系。
    这里别用for循环,你能确定父节点是固定的数量?function getClickElement(obj) {
        if (!obj) return;
        while(obj = obj.parentNode) {
            document.write(obj.nodeName + "<br/>");
        }
    }
      

  3.   

    <html>
    <body><BR/><script>
    function getClickElement(obj)
    {
    var pnode=obj;
    var i=0;
    for (i=0;i<10;i++)
    {
    pnode=pnode.parentNode;
    document.write(pnode.nodeName+"<BR/>");
    }
    }
    </script>JAVASCRIPT information<form action="post.php" method="post">
    Enter your name: <input type="text" name="name" /><BR/>
    Enter your age: <input type="text" name="age" /><BR/>
    <input type="button" value="post确认" onclick="getClickElement(this)"/>
    </form><BR/><BR/><BR/></body></html>我的代码如上...只是测试代码而已.不知道为什么不能运行..只显示一行结果
    FORM
      

  4.   

    关键的地方你是用document.write输出
    当页面加载完毕(相当于document.close)使用write将导致document重新构造,之前的元素随之消失简单说:打印结果的同时破坏列元素的结构。<html>
    <body><BR/>
    <script>
    function getClickElement(obj) {
    var msg = "";
    while (obj = obj.parentNode) {
    msg += obj.nodeName + "<BR/>";
    }
    document.write(msg);
        document.close();
    }
    </script>JAVASCRIPT information<form action="post.php" method="post">
    Enter your name: <input type="text" name="name" /><BR/>
    Enter your age: <input type="text" name="age" /><BR/>
    <input type="button" value="post确认" onclick="getClickElement(this)"/>
    </form><BR/><BR/><BR/>
    </body></html>