jQuery selector for attributes with values greater

2020-07-09 09:12发布

问题:

i have a few div like above

<div class="roomnamecta" data-price="1189" data-adult="3">Room 1</div>
<div class="roomnamecta" data-price="578" data-adult="1">Room 2</div>
<div class="roomnamecta" data-price="650" data-adult="2">Room 3</div>

In Jquery i'm able for exemple to display div wich data-adult= a specific value

// init (first i'm hidding all my divs)
$('.roomnamecta').hide();
// now i'm just showing depending on "data-adult" value
$('.roomnamecta[data-adult="3"]').show();

What i would like to do is something like this

$('.roomnamecta[data-adult>="3"]').show();
// doesn't work

And better what i want to accomplish is to do for exemple

$('.roomnamecta[data-adult>="3"],.roomnamecta[data-price>="1100"]').show();

How to write such a query, do i have to use object? how?

回答1:

Since you can't accomplish this with an attribute selector (like you're trying to do), you would have to iterate over the elements and check.

For instance, you could use the .filter() method to return the elements whose data-adult attribute value is greater than or equal to 3:

Example Here

$('.roomnamecta[data-adult]').filter(function () {
    return $(this).data('adult') >= 3;
}).show();

For your second query, you could use:

Example Here

$('.roomnamecta[data-adult], .roomnamecta[data-price]').filter(function () {
    return $(this).data('adult') >= 3 || $(this).data('price') >= 1100;
}).show();