在表格中的特定td下添加项目

时间:2016-05-21 09:00:33

标签: javascript jquery html html-table

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

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

输入:“这就是我想要达到的目标”

结果:

enter image description here

目前,我有以下内容为每个单词的第一个字母构建标题,但这些字母重复出现。我现在需要建立表体。我可以使用相同的逻辑将每个单词放入表中,但我正在努力做的是在表的相应部分下添加单词。例如,单词'This'位于第一行的第三个<td>中。我做了很多尝试,但没有一个工作,所以将make tableBody函数作为空白画布。我的一个想法是在第一行中为每个项目添加第一个字母的id,然后我可以将其用于完整的单词,但是无法将它们放在相应的第一个字母下面。

var $ = jQuery.noConflict();

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

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

    app.checkWord = {

    splitWords: function() {

        $(".calculate").click(function(){
            app.checkWord.firstLetter();
            var result = $("#text-input").val().split(" ");
            app.createTable.tableHeader(result.sort());
        });
        
    },

    firstLetter: function() {
        
    }
},

app.createTable = {

    tableHeader: function(sentence) {  
        $.each(sentence, function(index, item) {
            $(".words-row").append("<td>" + sentence[index].charAt(0).toUpperCase() + "</td>");
        });        
    },

    tableBody: function() {

    }

}

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

  $(document).ready(app.docOnReady.init);
  $(window).resize(app.docOnResize.init);

})(jQuery);
table {
  border-collapse: collapse;
}
table,
th,
td {
  border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="header">
</div>

<div id="main">

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

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

</div>

1 个答案:

答案 0 :(得分:0)

我会指出你正确的方向,而不是给你想要的答案。

忘记使用DOM Tree了。找出哪些单词属于哪个类别,然后才会对数据表示进行渲染。

这是一个快速而又脏的javascript,向您展示如何通过首字母将字符串拆分为多维数组。

然后,您将获取数组并将其输出到表行,或者您想要使用它做什么。

// Your string
var str = 'this is what i want to achieve';

// Split string by space -> creates array of words.
var arr = str.split(' ');

// Resulting array
var result = new Array();

// Go through all words and assing them to resulting multi-dimensional array
for (var i=0; i< arr.length; i++){

  if (typeof result[arr[i][0]] == 'undefined' )
  	result[arr[i][0]] = new Array();
    
  result[arr[i][0]].push(arr[i]);
}


/* Print output */
function dump(obj) {
    var out = '';
    for (var i in obj) {
        out += i + ": " + obj[i] + "\n";
    }

    var pre = document.createElement('pre');
    pre.innerHTML = out;
    document.body.appendChild(pre)
}

dump(result);

相关问题