2013-11-03 88 views
0

我有一個5x5的HTML表格,也就是說,每個tr都有5個td,每個td都有一個輸入字段,我想要解析值,每個td都有數據屬性數據行和數據列。這是我想到的,但它是越野車,我該怎麼做?解析HTML表格中的值

tds = $('td') 
marker = 0 
thisSet = [] 
table = [] 

for td in tds 
thisRow = parseInt($(td).attr('data-row')) 

if marker == thisRow 
    rc = "#{$(td).attr('data-row')}-#{$(td).attr('data-column')}" 
    thisSet.push ({data: rc}) 
    console.log "marker:#{marker}, thisRow:#{thisRow}" 
else 
    rc = "#{$(td).attr('data-row')}-#{$(td).attr('data-column')}" 
    thisSet.push ({data: rc}) 
    marker = thisRow 
    console.log "marker:#{marker}, thisRow:#{thisRow}" 
    table.push thisSet 
    thisSet = [] 

console.log table 
console.log _.flatten(table).length 

UPDATE:好,工作多一點就可以了,現在我有4行分析,而不是第5行,那裏有東西丟失,但4行解析罰款。

tds = $('td') 
currentRow = 0 
thisSet = [] 
table = [] 
for td in tds 
    thisRow = parseInt($(td).attr('data-row')) 
    rc = "#{$(td).attr('data-row')}-#{$(td).attr('data-column')}" 

if currentRow != thisRow 
    table.push thisSet 
    thisSet = [] 
    thisSet.push ({data: rc}) 
    currentRow = thisRow 
else 
    thisSet.push ({data: rc}) 

console.log table 
console.log _.flatten(table).length 
+0

的{}在for ... in循環,也是你的,如果(){}其他{}邏輯。 – joshstrike

+0

@joshstrike注意'coffeescript'標籤 –

+0

@koala_dev ...啊。抱歉。錯過了 – joshstrike

回答

1

我可以做這樣的:首先,你缺乏

table = [] 
table.push([]) for num in [0...5] 

tds = $('td') 

for td in tds 
    row = parseInt(td.attr(data-row)) 
    col = parseInt(td.attr(data-column)) 

    table[row][col] = { data: "#{row}-#{col}" } 

console.log table