4

I am hiding divs until a specific amount of time has passed, at which I am attempting to tell jQuery to show a specific div with the corresponding time.

HTML

<div class="content">
    <div class="item" value="00:15">
        <p>Some text</p>
    </div>
    <div class="item" value="00:30">
        <p>More text</p>
    </div>
    <div class="item" value="01:00">
        <p>Even more text</p>
    </div>
</div>

JS

$('.content').children().hide();

// some timer function returning timeElapsed

var myTime = '01:00';
if (timeElapsed == myTime) {
  $('.item').attr('value', myTime).show();
}

What's happening is all the .item divs are showing when the if statement is triggered, instead of the one specified by var myTime. What needs to be changed?

4

4 回答 4

4

You can use attribute equals selector

if (timeElapsed == myTime) {
    $('.item[value='+myTime+']').show();
}
于 2013-05-04T17:34:56.853 回答
1

Try this:

if (timeElapsed === myTime) {
  $('.item[value="' + myTime + '"]').show();
}
于 2013-05-04T17:35:10.507 回答
1

What this line is doing $('.item').attr('value', myTime).show(); is grabbing all item elements setting the attr with myTime on all .item elements and triggering show.

If you need an better selector, namely attribute equals

$('.item[value="' + myTime + '"]')

Another way to do it that doesn't result in querying the dom again would be setting up the timers in a simple each() loop.

You should be using data-* attributes might work better for you along with jQuery.

Also doing it in total seconds will make working with the value a bit easier as well.

<div class="content">
    <div class="item" data-seconds="15">
        <p>Some text</p>
    </div>
    <div class="item" data-seconds="30">
        <p>More text</p>
    </div>
    <div class="item" data-seconds="60">
        <p>Even more text</p>
    </div>
</div>

$("div.item").hide().each(function(index, item){
    var $item = $(this);
    setTimeout(function(){
      $item.show();
    }, $item.data("seconds") * 100);
});

Example on jsfiddle

于 2013-05-04T17:45:32.993 回答
0
if (timeElapsed == myTime) {
    $('.item[value=' + myTime + ']').show();
}

or

if (timeElapsed == myTime) {
    $('.item').filter('[value=' + myTime + ']').show();
}

From the looks of it, you don't need the if statement either.

于 2013-05-04T17:53:59.520 回答