简体   繁体   中英

How to find an attribute value for some Element in a Class with jQuery?

I need help guys, i have a class .content , this class have attribute called data-time , i want to get the value from data-time attribute, after that i want to show this value in .content class. But my code is not work better.

My HTML Code

    <div class="content first" data-time="200"> </div>
    <div class="content second" data-time="300"> </div>
    <div class="content third" data-time="400"> </div>
    <div class="content fourth" data-time="500"> </div>

My jQuery Code

var time = $(this).find('.content').attr('data-time');
$(this).find('.content').text(time);

Please anybody to help me.

try use .each to iterate

$(".content", this ).each(function(){

    $(this).text( $(this).attr("data-time") );

});

See in fiddle -> http://jsfiddle.net/Castrolol/vAnmf/

As per my understanding you require this

 $(function () {
     $('.content').each(function () {
         var time1 = $(this).attr('data-time');

         $(this).text(time1);
     });
 });

DEMO

Try this one..It will output your attribute text with no extra spaces at start and end of the string

  $(".content").each(function () {
      $(this).text($.trim($(this).attr("data-time")));
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM