且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将表数组值附加到另一个数组

更新时间:2022-10-19 20:23:16

Restructure your code to have a method to redraw UI and to enable event listeners:

function redraw (obj) {

  var $header = $('<tr>'),
    cols = 0,
    bodyString = ''

  $.each(obj, function (key, values) {
    cols = Math.max(cols, values.length) // find the longest
    $header.append($('<th/>').text(key + ': ' + values.length))
  })
  for (var i = 0; i < cols; i++) { // or use .map, but this is more undertandable for beginners
    bodyString += '<tr>'
    $.each(obj, function (key, values) {
      bodyString += '<td>' +
        (values[i] ? values[i] : '') + // ternary - instead of using if/else
        '</td>'
    })
    bodyString += '</tr>'
  }
  $('.fruitsTableClass thead').html($header)
  $('.fruitsTableClass tbody').html(bodyString)
}

function listener (obj) {
  tbl = document.getElementById('fruitsTable')
  if (tbl != null) {
    for (var i = 0; i < tbl.rows.length; i++) {
      for (var j = 0; j < tbl.rows[i].cells.length; j++)
        tbl.rows[i].cells[j].onclick = function () {
          getval(this)
          obj[key2].push(this.innerHTML)
          redraw(obj)
          listener(obj)
        };
    }
  }
}

function getval (cel) {
  alert(cel.innerHTML)
}

redraw(obj)
listener(obj)

JSFiddle - https://jsfiddle.net/gnm8wv5f/

相关阅读

技术问答最新文章