解析HTML表中的值

时间:2013-11-03 05:11:48

标签: javascript algorithm data-structures coffeescript

我有一个5x5的HTML表,也就是说,每个tr有5个td,每个td有一个输入字段,我想解析它的值,每个td都有数据行和数据的数据属性 - 柱。这就是我想出来的,但它有缺陷,我该怎么做?

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

更新:好的,再多做一点,现在我解析了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

1 个答案:

答案 0 :(得分: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