这是我蹩脚的第一次尝试。我想得到一个表中每个独特单词的计数。基于该计数,我想改变文本的大小。我试图通过在表的每一列上添加一个不同的类来实现这一点(因此表的列中的第一个单元格具有'first'类,而表中的第二个单元格具有'second'类每一栏。我正在尝试以编程方式执行此操作,因此我不必为可能填充表格的每个单词强制使用正则表达式。任何朝向正确方向的指导都将很棒:)
JS
$(function()
{
var searchTerms = $('.thetable').text(); //get all search terms in table
var words[] = text.split(''); //make them into an array
for(var count =0, count < words.length; count++)
{
$('#results').append(words[i]);
}
if($('.first').length > 1).css({'font-size': 13 + 'px'}))
else if($'.second').length > 1 && < 3).css({'font-size': 16 + 'px'}))
else($('.third').length > 3).css({'font-size':18 + 'px'))
}
});
HTML
<body>
<div id="results"></div>
<table style="width: 35%" cellspacing="1" class="thetable">
<tr >
<td class="first">one</td>
<td class="second">three</td>
<td class="third">five </td>
<td class="fourth">six</td>
<td class="fifth">ten</td>
</tr>
<tr>
<td class="first">one</td>
<td class="second">three</td>
<td class="third">five</td>
<td class="fourth">seven</td>
<td class="fifth">ten</td>
</tr>
<tr>
<td class="first">one</td>
<td class="second">four</td>
<td class="third">five</td>
<td class="fourth">eight</td>
<td class="fifth">ten</td>
</tr>
<tr>
<td class="first">two</td>
<td class="second">four</td>
<td class="third">five</td>
<td class="fourth">nine</td>
<td class="fifth">ten</td>
</tr>
</table>
</body>
答案 0 :(得分:2)
为什么不使用像$('table.thetable tr').find('td:first')
这样的东西来获取第一个单元格?您不必经历明确标记类的繁琐工作。或者更明确,find('td:eq(2)')
等等。
答案 1 :(得分:1)
var tds = $('table td');
var words = [];
tds.each(function() {
var word = $(this).html();
var num = $('td:contains(' + word.toLowerCase().trim() + ')', 'table').length;
if (num <=1) {
$(this).css('font-size', '13px');
} else if(num > 1 && num < 3) {
$(this).css('font-size', '23px');
} else if (num > 3) {
$(this).css('font-size', '60px');
}
});
答案 2 :(得分:1)
您需要将数组缩减为单词列表,并且您可能需要对每个单词进行计数:
var words[] = text.split(''); //make them into an array
var o={}
for(var count =0, count < words.length; count++)
{
if(words[i] in o)o[words[i]]++; else o[words[i]]=1;
}
你想按计数(最多到最少)对单词列表进行排序吗?
var i, wordsByCount = [];
for(i in o)wordsByCount.push([o[i],i]);
worsByCount = wordsByCount.sort(sortFunc);
function sortFunc(a,b){return b[0]-a[0];}
for(var count =0, count < wordsByCount.length; count++)
{
$('#results').append(wordsByCount[i][1]);
}
或者如果你想显示单词和出现次数
for(var count =0, count < words.length; count++)
{
$('#results').append(wordsByCount[i][1] + " (" + wordsByCount[i][0] + ")");
}