jQuery的:检查是否列包含一定的价值
我有一个包含各种值的标准表。相同的值可能会出现在不同的阵,但不相同的列中。
I have a standard table that contains various values. The same value may appear in different TDs but not within the same column.
示例:
<table id="myTable">
<tr>
<td>text1</td>
<td>text2</td>
<td>text3</td>
</tr>
<tr>
<td>text4</td>
<td>text5</td>
<td>text6</td>
</tr>
<!--more TRs...-->
</table>
有没有一种方法,我可以使用jQuery检查某个列是否包含特定值,并返回1,如果是或0,如果没有?
Is there a way I can use jQuery to check whether a certain column contains a certain value and return 1 if yes or 0 if no ?
示例:
当上述应用此为第二列,检查文本2
,它应该返回1;如果我检查 text5
它应该返回1为好;如果我检查 text6
它应该返回0作为在此列不存在。
Example:
When applying this to the second column above and check for "text2
" it should return 1; if I check for "text5
" it should return 1 as well; if I check for "text6
" it should return 0 as not existing in this column.
我想开始类似的:
$('#myTable td:nth-child(2)').each(function() {
//...
});
感谢任何帮助,蒂姆。
Thanks for any help with this, Tim.
像这样
$.fn.colCheck = function(col, text) {
var c = Array.isArray(col) ? col : [col],
t = this,
a = [];
$.each(c, function(_, v){
a.push(
t.find('tr td').filter(function() {
return $(this).index() === (v-1) && $.trim($(this).text()) === text;
}).length
);
});
return a.length === 1 ? a[0] : a;
}
要用于像
$('#myTable').colCheck([1,2,3], 'text5'); // pass array, return array [0,1,0]
$('#myTable').colCheck(2, 'text2'); // 1
将返回在给定的列中的文字的出现的次数。
would return the number of occurences of that text in the given column.