JQuery.show () div with attribute of specific value

I hide the divs until a certain amount of time has passed in which I try to tell jQuery to show a specific div with the appropriate 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 happens is that all .item show when the if statement is run, and not the one specified by var myTime . What needs to be changed?

+4
source share
4 answers

You can use attribute equal to selector

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

Try the following:

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

What does this line do $('.item').attr('value', myTime).show(); , captures all item elements, setting attr with myTime for all .item elements and starting the show.

If you need a better selector, namely attribute equals

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

Another way to do this that will not result in a query in dom again is to set the timers in a simple each() loop.

You should use data-* attributes, which may work better for you with jQuery.

Besides doing this in full seconds, you will also work with this value.

 <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); }); 

Jsfiddle example

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

or

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

In appearance, you do not need an if .

0
source

Source: https://habr.com/ru/post/1479160/


All Articles