JQuery Contains Selector - Multiple Text Items

2019-07-24 22:05发布

问题:

I am new to JQuery and maybe am missing the obvious, but how can I filter a table using the contains selector but have it look for multiple strings using an OR operator. In other words, I would like rows containing "Red" OR "Yellow" to be hidden.

So far I have this which works by hiding all rows except the given date:

$(function()
{
    $('div#WebPartWPQ5 table.ms-summarycustombody tr:not(:contains("10/27/2009"))')
        .hide();
});

As added challenge, what I am really trying to do is write a hidden script that calulates a date range and then removes table rows containing dates not falling into that range.

Thank you in advance.

John

回答1:

Separate the different selector strings with commas.

$('table tr.red, table tr.yellow').hide()


回答2:

Do you have control over the html in your page?

If so, consider adding a class "date" (or "colour") to the appropriate td element of each row. Then - instead of using :contains - which is highly likely to suffer from cross-browser compatibility issues, iterate over the table rows, accessing $('tr td.date').val() and performing whatever tests you need to.

Additionally, I would suggest using date.js (http://www.datejs.com/) to simplify the date handling.

var datestart = Date();
var dateend = Date();

$('div#WebPartWPQ5 table.ms-summarycustombody tr td.date').each(function(){
    var date = Date.parse( $(this).val() );
    if (date.between(datestart, dateend === true)) {
        $(this).parent().hide(); //your logic here
    }
});

And another example that uses the .filter() method (see http://docs.jquery.com/Traversing/filter#fn).

var datestart = Date();
var dateend = Date();

$('div#WebPartWPQ5 table.ms-summarycustombody tr').filter(function(){
    var date = Date.parse( $('td.date', this).val() );
    return date.between(datestart, dateend) === true;
}).hide(); //your logic here