从对象jquery / javascript创建一个表

时间:2016-05-21 15:03:38

标签: javascript jquery html-table

我正在尝试实施以下内容。

用户在文本框中输入一个句子,然后创建一个表格。一个例子就是这个。

输入:"This is what I want to achieve"

结果:

enter image description here

目前,根据我的代码,有一个对象如下:

{t: ["this", "to"], i: ["is", "i"], w: ["what", "want"], a: ["achieve"]};

以下是我当前的代码(also see jsfiddle here)。

我能够获取输入字符串并创建一个包含每个单词首字母的行的表。

HTML

<textarea id="text-input" name="textarea" rows="5" cols="25">This is what I want to achieve</textarea>
<button class="calculate">Calculate</button>

<table>
  <tbody>
    <tr class="words-header"></tr>
  </tbody>
</table>

的Javascript

$(document).ready(function() {
  $(".calculate").click(function() {
    var result = {},
      arr = [];
    var array = $("#text-input").val().toLowerCase().split(" ");

    for (var i = 0; i < array.length; i++) {
      if (typeof result[array[i][0]] == 'undefined') {
        result[array[i][0]] = [];
      }
      result[array[i][0]].push(arr[i]);
    }
    for (var key in result) {
      $(".words-header").append("<td>" + key.toUpperCase() + "</td>");
    }
  });
});

我相信决赛桌如果有帮助就应该是这样的:

<table>
    <tr>
      <td>A</td>
      <td>I</td>
      <td>T</td>
      <td>W</td>
    </tr>
    <tr>
      <td>achieve</td>
      <td>is</td>
      <td>this</td>
      <td>what</td>
    </tr>
    <tr>
       <td> </td>
       <td>i</td>
       <td>to</td>
       <td>want</td>
    </tr>
</table>

1 个答案:

答案 0 :(得分:0)

您可以这样做(点击下面的运行代码段按钮试试):

var app = app || {};
(function() {
    "use strict";

    var result, arr;

    app.initialize = {
        init: function() {
            app.splitWords.init();
        }
    };

    app.splitWords = {
        init: function() {
            $(".calculate").click(function() {
                result = [];
                arr = $("#text-input").val().split(" ");
                app.createMultiArray.init(arr);
            });
        }
    };

    app.createMultiArray = {
        init: function(array) {
            for (var i = 0; i < array.length; i++) {
                var letter = array[i][0].toLowerCase();
                if (typeof result[letter] == 'undefined') {
                    result[letter] = [];
                }
                result[letter].push(array[i]);
            }
            // I added this method
            app.buildTable.init(result);
        }
    };

    app.buildTable = {
        init: function(result) {
            var headers  = Object.keys(result),
                max_rows = 0,
                rows_html = '';
            headers.sort();
            app.createHeaders.init(headers);
            // Determine how many rows you'll need
            for (var i = 0; i < headers.length; i++) {
                if(result[headers[i]].length > max_rows) { max_rows = result[headers[i]].length; }
            }
            // Loop "max_rows" times
            for (var i = 0; i < max_rows; i++) {
                rows_html += '<tr>';
                // Loop through all letters
                for(var j = 0; j < headers.length; j++) {
                  rows_html += '<td>';
                  if(i < result[headers[j]].length) {
                      rows_html += result[headers[j]][i];
                  }
                  rows_html += '</td>';
                }
                rows_html += '</tr>';
            }
            $(".words-header").after(rows_html);
        }
    };
  
    app.createHeaders = {
        init: function(headers) {
            // Empty the table in case of multiple tries
            $(".words-header").parent().html('<tr class="words-header"></tr>');
            for (var i = 0; i < headers.length; i++) {
                $(".words-header").append("<td>" + headers[i].toUpperCase() + "</td>");
            }
        }
    };

    app.docOnReady = {
        init: function() {
            app.initialize.init();
        }
    };

    $(document).ready(app.docOnReady.init);

})(jQuery);
#results-table table{ border-collapse: collapse; } #results-table td{ border: 1px solid #000; padding: .2em;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<textarea id="text-input" name="textarea" rows="5" cols="25">This is what I want to achieve</textarea>
<button class="calculate">Calculate</button>

<div id="results-table">
  <table>
    <tbody>
      <tr class="words-header"></tr>
    </tbody>
  </table>
</div>