Why is jQuery returning each character of the contents of my span element when I loop it?
Ok, I have bunch of span with a开发者_如何学Cn endtime class. I want to get each of the contents independently from the others.
<span class='endtime'>
2011-03-29 00:01:03
</span>
<span class='endtime'>
2011-03-31 19:20:11
</span>
<span class='endtime'>
2011-03-28 19:00:12
</span>
But the problem is, when I do this:
var text = $('.endtime').text();
for(var i = 0; i < text.length; i++) {
$('.counter').countdown({
until: text[i],
format: 'HMS'
})
}
The contents of the text only have 1 character? How to make it return the whole characters?
When calling .text()
you can optionally pass in a function to execute on each item in the collection.
$("span.endtime").text(function(i, text){
$('.counter').countdown({
until: text,
format: 'HMS'
})
});
Simple example on jsfiddle.
text()
returns a string of the first element, not all texts of all elements!
To iterate over all elements, try this:
$('.endtime').each(function(){
var text = $(this).text();
//something with text
});
If you really want an array you can also write:
var texts = $('.endtime')
.map(function(){return $(this).text();})
.get();
// texts is now an array of strings.
// rest of the code is the same.
try this code
var text = $('.endtime');
for(var i = 0; i < text.length; i++) {
$('.counter').countdown({
until: text[i].text(),
format: 'HMS'
})
}
精彩评论