开发者

JQuery, show an element based on 2 attribute conditions

开发者 https://www.devze.com 2023-02-05 15:25 出处:网络
I was wondering if anyone knew of a way of selecting a DIV based on 2 of its attributes meeting a certain criteria using JQuery?Say for example I have a variable called \'time\', now if data-in and da

I was wondering if anyone knew of a way of selecting a DIV based on 2 of its attributes meeting a certain criteria using JQuery? Say for example I have a variable called 'time', now if data-in and data-out (below) are 'seconds', how would you show the relevant DIV based on the 'time' variable. Assume all the DIVs below are hidden by CSS to start with.

For example if 'time'=15 it would show slide1 because it's betwe开发者_JAVA百科en data-in (10) and data-out (20), and if 'time'=73 it would show slide4 (between data-in 70 and data-out 80).

Here is the code (very basic),

<div id="slide1" data-in="10" data-out="20" name="slide1"></div> 
<div id="slide2" data-in="30" data-out="40" name="slide2"></div> 
<div id="slide3" data-in="50" data-out="60" name="slide3"></div> 
<div id="slide4" data-in="70" data-out="80" name="slide4"></div> 
<div id="slide5" data-in="90" data-out="100" name="slide5"></div>

Thanks in advance.


You could do it like this using filter()(docs) :

Example: http://jsfiddle.net/3vDcb/4/

var time = 35;

$('div[name^=slide]').filter(function() {
    var data_in = $(this).attr('data-in');
    var data_out = $(this).attr('data-out');

    return time >= data_in && time <= data_out;
}).show();

EDIT: Fixed an error due to gaps in ranges.


You need to find a way to iterate over those elements. You can add a class, you can use a "starts-with" selector ('[id^=slide]'), or you can use a double attribute selector like this:

var time = 15;
jQuery('[data-in][data-out]').each(function(index, range){
    var $this = $(this),
        dataIn  = $this.attr('data-in'),
        dataOut = $this.attr('data-out');

    if(dataIn < time && time < dataOut) {
        $this.show();
    }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消