2010-10-05 60 views
1

我有這個腳本,我認爲它比較簡單。它基本上構成了iframe內容的樹形佈局。當樹的某些部分懸停時,其相應的iframe元素將被「選中」。但是這對我的生活並不奏效。下面是一些快速的半僞代碼:來自另一個元素的參考HTML節點

function traverseTree(c,o){ 
    //c = the tree subset to put more stuff in 
    //o = the element to traverse 
    var treeNode = D.createElement('div'); 
    c.appendChild(treeNode); 
    treeNode.innerHTML = o.tagName; 
    treeNode['refNode'] = o; 
    treeNode.addEventListener('mouseover',check,false); 
    loop(o.children){ 
     traverseTree(treeNode,o.child); 
    } 
} 
function check(e){ 
    alert(e.target.refNode); 
} 

e.target.refNode出現問題。它只給出第一個節點(或HTML標籤)的元素引用。其餘的都是未定義的。但是,當我在設置它後立即檢查treeNode.refNode時,它總是正確的。

編輯:

所以,我做了一個簡單的測試:

<html> 
<head> 
    <title>Test</title> 
    <script> 
     window.onload = function(){ 
      createTree(document.getElementById('tree'), 
       document.getElementById('page').contentWindow.document); 
     } 

     function createTree(c,o){ 
      //get list of children 
      var children = o.childNodes; 
      //loop through them and display them 
      for (var i=0;i<children.length;i++){ 
       if (typeof(children[i].tagName) !== 'undefined'){ 
        //Create a tree node 
        var node = document.createElement('div'); 
        if (children[i].childNodes.length > 0){ 
         node.style.borderLeft = '1px dotted black'; 
         node.style.marginLeft = '15px'; 
        } 
        c.appendChild(node); 
        //Reference to the actual node 
        node.refNode = children[i]; 
        //Add events 
        node.addEventListener('mouseover',selectNode,false); 
        //Display what type of tag it is 
        node.innerHTML += "&lt;"+children[i].tagName.toLowerCase()+"&gt;"; 
        //Add in its child nodes 
        createTree(node,children[i]); 
        //ending tag... CRASHES THE PROGRAM 
        node.innerHTML += "&lt;/"+children[i].tagName.toLowerCase()+"&gt;"; 
       } 
      } 
     } 

     function selectNode(e){ 
      document.getElementById('info').innerHTML = e.target.refNode; 
     } 
    </script> 
</head> 
<body> 
    <iframe id='page' src='some_page.html'></iframe> 
    <div id='info' style='border-bottom:1px solid red;margin-bottom:10px;'></div> 
    <div id='tree'></div> 
</body> 
</html> 

,我想通了,追加子樹節點之後增加的innerHTML被帶走了孩子們的refNode財產。所以,這就是問題發生的地方。

+0

查看僞代碼時很難發現可能會出錯的地方。如果你可以發佈一個工作示例,這將有所幫助。 – gilly3 2010-10-06 00:02:58

回答

1

所以,我想解決方案只是將.innerHtml更改爲.appendChild(document.createTextNode(...))。我的腳本僅用於本地使用,並且只爲FF3 +構建,所以除此之外,應該沒有問題。

0

您不能在元素的屬性中存儲對象。如果檢查屬性,則顯示的內容是指定節點的字符串表示形式。如果你會使用jQuery,你可以使用jQuery.data()

+0

不,但您可以將對象存儲爲元素的屬性。將其粘貼到瀏覽器的地址欄中:javascript:var o = document.body.appendChild(document.createElement(「div」)); o ['foo'] = {prop:「value」};警報(o.foo.prop); – gilly3 2010-10-05 23:52:55

+0

如果你認爲,添加屬性是一個好主意,看看這個:http://perfectionkills.com/whats-wrong-with-extending-the-dom/ – 2010-10-06 02:02:17

+0

那麼,小的DOM擴展將不會真正重要長遠來看,特別是如果它不會像我的腳本那樣分發的話。 – Azmisov 2010-10-06 02:46:30