2011-11-09 113 views
3

我正在做一個小jQuery + greasemonkey,我試圖用來重做一個內部工作網站的接口,我必須使用每一天來嘗試使它更有用。從舊的HTML DOM元素創建JSON

我已經到了抓取頁面並將其粘貼在div中的階段。 我可以使用一些jQuery選擇器來識別表格im之後的數據行。

然而,它的舊的詳細html例如

<tr style="font-family:blaaa"> 
    <td>1.</td> 
    <td><a target="_BLANK" href="url=my bugs">13312800</a></td> 
    <td sorttable_customkey="20110512"> 
     12-MAY-11 
    </td> 
    <td> Many more tds </td> 
</tr> 

我有另一個tr有信息我可能在一個階段喜歡用作我的json中的鍵。

最重要的方法是抓取重要數據?我希望它最終駐留在一些JSON中?正則表達式?模板?

+0

我認爲你的意思是*刮*數據,而不是報廢數據。 –

+0

哈哈哈的確是史蒂文 – wmitchell

回答

1

您必須在這裏做一些遞歸,並應用每個TR標籤中的選擇器。

var recordset = []; 
$('table.myTable tr').each(function(i,e) { 
    var record = { 
     id: $(e).find('td:nthchild(2) a').text(), 
     url: $(e).find('td:nthchild(2) a').attr('href'), 
     date: $(e).find('td:nthchild(3)').text(), 
     comment: $(e).find('td:nthchild(4)').text() 
    }; 
    recordset.push(record); 
}); 

// Here you have complete recorset: 
console.log(recordset); 

// To output some JSON in a string 
for (var i = 0; i < recordset.length; i ++) { 
    alert($.param(recordset[i])); 
} 

如果要使用特定的DOM嘗試使用jQuery templates,喜歡這個輸出數據特別是{{每個}}渲染項目列表的標籤,我發現他們很容易使用和非常靈活的渲染JSON數據。

+0

謝謝史蒂文這是什麼即時消息後。 – wmitchell