使用jQuery动态更改表中的rowspan

时间:2016-10-06 08:59:05

标签: javascript jquery

当用户可以合并行和列时,我正在尝试构建表。我已经获得了列的代码正常工作,并且行也几乎存在 - 但是,当我将行间距从3变为2时,我会添加一个额外的列。

你可以在this fiddle中看到我的意思。

这是我的代码:

function growRow(td, span, cell_content) {
  var cell_content = (typeof cell_content === 'undefined') ? '<td></td>' : cell_content
  var row = td.closest("tr")
  var index = td.index()
  var old_span = (typeof td.attr('rowspan') === 'undefined') ? 1 : Number(td.attr('rowspan'))
  var table = row.parents('table')
  var content

  td.attr('rowspan', span)

  if (span > old_span) {
    // If we want to merge cells, this is easy
    var selector = "tr:lt(" + (span - 1) + ")"

    row.nextAll(selector).each(function () {
        // Grab the content from each cell
      content = $("td:eq(" + index + ")", $(this)).html()
      $("td:eq(" + index + ")", $(this)).remove()
    })

    // Get the next cell down
    row = $('tr:eq('+ span +')')
    // Append the content to make it look as though the cells are 'moving down'
    row.find('td:eq('+ index +')').html(content)
  } else {
    // This is where I'm having problems
    // Get the number of cells we need to put back
    count = old_span - span
    // Work through the rows
    for (var i=0; i < count ; i++) {
      // Get the row at the right index
      r = $(row.nextAll()[i])
      if (index == 0) {
      // If we're at the beginning of a row, we need to prepend
        r.prepend(cell_content)
      } else {
      // Otherwise use nth-child to append in the right place
        r.find('td:nth-child(' + index + ')').after(cell_content)
      }
    }
  }

  return td
}

任何帮助都会非常感激,因为我现在已经为DAYS做过了!

1 个答案:

答案 0 :(得分:1)

您需要获取r + count偏移的行吗?而不只是r