我需要查找td.aws中的字符串是否出现超过3次,如果出现这种情况,请将该字符串放入新列表中。
我有一张这样的表:
<table width="100%" cellspacing="0" cellpadding="2" border="1" class="aws_data">
<tbody><tr bgcolor="#ECECEC"><th>URL (1,908)</th></tr>
<tr><td class="aws">/images/bullet3.png</td></tr>
<tr><td class="aws">/pdf-signing-tool/ErrorCode.properties</td></tr>
<tr><td class="aws">/pdf-signing-tool/Display.properties</td></tr>
<tr><td class="aws">/evcert.cfm</td></tr>
<tr><td class="aws">/evcert.cfm</td></tr>
<tr><td class="aws">/evcert.cfm</td></tr>
<tr><td class="aws">/evcert.cfm</td></tr>
<tr><td class="aws">/repository/03</td></tr>
<tr><td class="aws">/repository/0</td></tr>
etc
<div id="problems"></div>
到目前为止,我有:
$('.aws').each(function(){
var temp = $(this).text();
var count = temp.match('/'+temp+'/g');
if (count.length > 3)
{
thisString = $(this).text();
$('#problems').append(thisString)
}
});
任何人都可以提供帮助,目前我刚刚收到JS错误“count is null”
答案 0 :(得分:2)
//store the counts for each "text" occurrence in a hash table
var countHash = {};
//iterate over your tds
$('.aws').each(function(){
//pull of the text
var temp = $(this).text();
//has it already been added to the list?
//see: 'countHash[temp] = false;' below.
if(countHash[temp] === false){return;}
//increment the occurrence count
//or set to 1 if this is the first occurrence.
countHash[temp] = (countHash[temp] || 0) + 1;
//have more than three been found?
if (countHash[temp] > 3)
{
//add to your list
$('#problems').append(temp);
//ignore future occurrences
countHash[temp] = false;
}
});
答案 1 :(得分:2)
应该使用new RegExp()
创建这样的正则表达式,如评论中所述。除此之外,如果使用括号和问号之类的东西,使用每个表格单元格的内部文本可能会导致无效的正则表达式。所以在这种情况下,我会建议反对。
您可以在迭代每个td.aws
时进行频率计数:
var frequencies = {};
$('td.aws').each(function() {
var key = $(this).text(),
freq = frequencies[key] || 0;
// increase the frequency and check if it goes above 3
if (++freq > 3) {
$('#problems').append(key);
freq = -Infinity;
}
frequencies[key] = freq;
});
对象frequencies
保留每个术语在其属性中的频率;一旦它达到一定数量,它就会做你需要的任何事情。
答案 2 :(得分:1)
var count = {};
$(".aws").each(function(i,v) {
var temp = $(v).text();
var current = count[temp];
if (!current) {
current = 0;
}
current++;
count[temp] = current;
if (current > 3) {
$("#problems").append("<p>"+temp+"</p>");
}
}
我不确定你是否要从旧列表中删除三次出现的项目,所以我没有添加
答案 3 :(得分:1)
您的问题出在此处:'/'+temp+'/g'
您无法在正则表达式文字中使用变量。您必须将正则表达式构建为字符串:
var tempRegex = new RegExp(temp, 'g');
var count = temp.match(tempRegex);
您的代码中似乎存在更大的逻辑问题。现在,您正在构建一个正则表达式,以查看文本是否与自身匹配,这始终是。我想你正试图搜索所有的TD以确定是否有重复。请尝试这种方法:
var items = [];
$('.aws').each(function(){
var currentText = $(this).text();
var duplicate = false;
for (var i = 0; i < items.length; i++) {
if (items[i].text === currentText) {
items[i].count++;
if (items[i].count > 2) {
console.log('found more than 2 of ' + currentText);
$('#problems').append(currentText)
}
duplicate = true;
break;
}
}
if (!duplicate) {
items.push({ text: currentText, count: 1});
}
});