如何遍历表的数据以查找特定文本?

时间:2013-08-07 16:17:55

标签: jquery

我有一个错误消息表,我希望在特定情况下加粗,以匹配完整的文本字符串。

这是表格:

<table width="1000px" border="0" cellpadding="0" class="search-messages">

    <logic:notEmpty name="pSRMessages" scope="request">
        <tr><td><h4><fmt:message key="SCN-1055"/></h4></td></tr>
        <logic:iterate id="rTMessage" name="pSRMessages" scope="request" >
            <tr><td><bean:write name="rTMessage"/></td></tr>
        </logic:iterate>
    </logic:notEmpty>
    <tr><td><h4><fmt:message key="SCN-1056"/></h4></td></tr>
    <logic:notEmpty name="pSMessages" scope="request">
        <logic:iterate id="message" name="pSMessages" scope="request" >
            <tr><td><bean:write name="message"/></td></tr>
        </logic:iterate>
    </logic:notEmpty>
    <logic:present name="pRList" scope="request" >
</table>

我写了这个方法,但是我收到了一个错误:

$(function () {
    if ($('.search-messages').each('tr').each('td').text() == 'Some specific line of text){
        $('this').css('font-weight', 'bold');
    }
});

js控制台中的错误消息:

Uncaught TypeError: Object tr has no method 'call'

在这种情况下,似乎我不能使用$('this')。如何识别与字符串匹配的当前td并更改它的css?

感谢。

4 个答案:

答案 0 :(得分:5)

您的each函数调用不正确,例如使用filter

$('.search-messages td').filter(function() {
    return $(this).text() == 'Some specific line of text';
}).css('font-weight', 'bold');

<强> jsFiddle

使用each

$('.search-messages tr td').each(function() {
    var el = $(this);
    if (el.text() == 'Some specific line of text') {
        el.css('font-weight', 'bold');
    }
});

<强> jsFiddle

答案 1 :(得分:2)

这样的事情怎么样:

$(".search-messages tr td").each(function(){ 
    var current = $(this);
    if(current.text() === "this will be bolded") { 
        current.toggleClass("special");
    }
});

这是一个小提示:http://jsfiddle.net/S9cs3/

答案 2 :(得分:1)

试试这个

$('.search-messages td').each(function() {
    if($(this).html() == 'Some specific line of text')
        $(this).css('font-weight', 'bold');
}

答案 3 :(得分:0)

我实际上有一个网站使用以下代码通过表格的行搜索“按字典搜索”并突出显示匹配项:

$('#search input').on('keyup', function(e) {
    var str = $(this).val().toLowerCase();
    var found = 0;
    if (str.length == 0 || e.keyCode == 27) { //user hit Esc or has no text in search box, clear out
        $('#search img').click();
    }
    else { //text has been entered, search for it
        $('#draft-board tbody tr').each(function() { //each row
            if ($(this).children('td.player').html().toLowerCase().search(str) > -1) { //search string found in current row! highlight it and scroll to it
                $(this).addClass('selected');
                if (found == 0) {
                    scroll(0,$(this).offset().top);
                }
                found += 1;
            }
            else { //search string not present in this row
                $(this).removeClass('selected');
            }
        });

        var tmp;
        if (found == 1) tmp = 'match';
        else tmp = 'matches';
        $('#search span').html(found + ' ' + tmp);
    }
});
相关问题