2016-05-13 52 views
0

我想使用樹行程來查找頁面上的表,插入列,然後根據每行第1個單元格中的值填充該列中的單元格。我做了很多研究,並且一直在失敗。任何命中將我推向正確的方向將不勝感激。使用樹行程修改表

document.ondblclick = addElement; 
 
var i = 1; 
 
function addElement() { 
 

 
    var allTextNodes = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT), 
 
    // some temp references for performance 
 
    tmptxt, 
 
    tmpnode, 
 
    // compile the RE and cache the replace string, for performance 
 
    cakeRE = "Investment" 
 
    replaceValue = "TestReplace"; 
 
    var allElementNodes = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT); 
 

 
    // iterate through all text nodes 
 
while (allTextNodes.nextNode()) { 
 
    tmpnode = allTextNodes.currentNode; 
 
    tmptxt = tmpnode.nodeValue; 
 
    tmpnode.nodeValue = tmptxt.replace(cakeRE, replaceValue); 
 
} 
 

 
    // iterate through all Element nodes 
 
while (allElementNodes.nextNode()) { 
 
    tmpnode = allElementNodes.currentNode; 
 

 
    //I know this is not even close to real code but I think it explains what i'm trying to do 
 

 
    IF (tmpnode.tagvalue = "table") 
 
    { 
 
    tmpnode.insertcolumn 
 
    } 
 
    If (tempnode.tagvalue = "tr" && Row.contains("Active")) 
 
    { 
 
    pupulate the cell from the previously created column with "Active Pending"; 
 
    } 
 

 
    
 
} 
 
}

function PopulateTable() { 
 
    var table = document.getElementsByTagName("table")[0]; 
 
    var rows = table.getElementsByTagName("tr")[0]; 
 
    for(var i = 0; i< rows.length; i++) { 
 
     var firstColumn = rows[0].getElementsByTagName("td")[0]; 
 
     //do your data aggregation here 
 
     var newCell = document.createElement("td"); 
 
     newCell.innerHTML = "some data";//create row here 
 
     rows[i].appendChild(newCell); 
 
    } 
 

 
}

回答

1

我認爲你可能在錯誤的方式去這件事。我建議不要在這種特殊情況下使用樹木行者。相反,你可以做一些簡單的事情,如下所示:

function PopulateTable() { 
    var table = document.getElementsByTagName("table")[0]; 
    var rows = table.getElementsByTagName("tr")[0]; 
    for(var i = 0; i< rows.length; i++) { 
     var firstColumn = rows[0].getElementsByTagName("td")[0]; 
     //do your data aggregation here 
    } 
    var newRow = document.createElement("tr"); 
    newRow.innerHTML = //create row here 
    table.appendChild(newRow); 
} 
+0

謝謝托馬斯,我會試試這個,我現在擺弄它。 – keatklein

+0

嗨托馬斯,newRow方法確實有效。我希望爲每一行添加一個新的單元格,像這樣(上面添加了新的代碼片斷)。 – keatklein