Selecting element and replacing text inside each()
I have a list which looks like the following:
<ul id="offers">
<li class="unique-id-here">
<span class="country">US</span>
<span class="clicks">192</span>
<span class="ctr">9%</span>
</li>
</ul>
And i am trying to update the .clicks with new values every 5 seconds.
So my though was, select each li -> get the u开发者_如何学JAVAnique-id-here -> save the id to a variable -> to a $.get request to request the clicks for that given id -> replace the current clicks with the new ones.
Problem is that i cannot seem to select the .clicks properly... this is what my jQuery code looks like:
var refreshId = setInterval(function() {
$("#offers li").each(function(){
var a = $(this).attr('class');
if(a) {
$.get("ajax.php", { opt: "stats", oid: a }, function(r) {
var j = eval('(' + r + ')');
$(this).find('.clicks').text('<strong>'+j.message.clicks+'%</strong>');
});
}
});
}, 5000);
Any ideas on how i can replace the .clicks value of each li field properly?
Help is much appreciated :)
Try:
var refreshId = setInterval(function() {
$("#offers li").each(function(){
var $li = $(this),
a = $li.attr('class');
if(a) {
$.get("ajax.php", { opt: "stats", oid: a }, function(r) {
var j = eval('(' + r + ')');
$li.find('.clicks').html('<strong>'+j.message.clicks+'%</strong>');
});
}
});
}, 5000);
You are using $(this)
inside the $.get
, which would refer to another object. Also, why are you using eval
? Why not return a JSON object to the request?
In addition, you are using text()
, however the string you pass to the parameter contains HTML (<strong>
). Thus, I switched text()
with html()
.
You could do:
var refreshId = setInterval(function() {
$("#offers li").each(function(){
var clicks = $(this).find('.clicks');
var a = $(this).attr('class');
if(a) {
$.get("ajax.php", { opt: "stats", oid: a }, function(r) {
var j = eval('(' + r + ')');
clicks.text('<strong>'+j.message.clicks+'%</strong>');
});
}
});
}, 5000);
i think that your problem is that $(this) inside the success function of tha AJAX call has not the scope you think. another thing you could do is:
var refreshId = setInterval(function() {
$("#offers li").each(function(){
var $that = $(this);
var a = $(this).attr('class');
if(a) {
$.get("ajax.php", { opt: "stats", oid: a }, function(r) {
var j = eval('(' + r + ')');
$that.find('.clicks').text('<strong>'+j.message.clicks+'%</strong>');
});
}
});
}, 5000);
精彩评论