jQuery: check if column contains certain value

孤人 提交于 2019-12-11 06:23:40

问题


I have a standard table that contains various values. The same value may appear in different TDs but not within the same column.

Example:

<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>

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 ?

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.

I was thinking of starting something like:

$('#myTable td:nth-child(2)').each(function() {
    //...
});

Thanks for any help with this, Tim.


回答1:


Something like this

$.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;
}

FIDDLE

to be used like

$('#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.




回答2:


like this:

<table id="myTable">
    <tr>
        <td>text1</td>
        <td class="check">text2</td>
        <td>text3</td>
    </tr>
    <tr>
        <td>text4</td>
        <td class="check">text5</td>
        <td>text6</td>
    </tr>
    //more TRs...
</table>

and jquery:

function check()

{

var flag = 0;
$('#myTable td.check').each(function(){


if($(this).html() == '')
{
flag = 0;
return flag;
}

else
{
flag = 1;
}


})
return flag;
}



回答3:


    function mycheck(what) {
        var result = 0;
        $( "#myTable td" ).each(function( index ) {
            var myval = $( this ).text();
            if ((index - 1) % 3 == 0 ) {
                if (myval == what) {
                    result = 1; return result; 
                }                   
            }               
        });
        return result;
    }


来源:https://stackoverflow.com/questions/23028594/jquery-check-if-column-contains-certain-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!