问题
I created a counter that count different numbers each, but when I choose all the elemnts in class it doesnt work...
$(document).ready(function() {
function change() {
/*
$(".test").each(function(i,domeElement){
var theNum = parseInt(this.html())+1;
this.html(theNum);
});
*/
//this works... the other one doesnt why?!?!
var theNum = parseInt($(".test").html()) + 1;
$(".test").html(theNum);
}
setInterval(change, 1000);
});
http://jsfiddle.net/DTyY7/
回答1:
You should use
$(this).html(theNum);
and not
this.html(theNum);
Because html()
is a jQuery function and this
(inside .each()
) is a domElement and so you must wrap it into a jQuery object
Fiddle here: http://jsfiddle.net/nicolapeluchetti/DTyY7/2/
回答2:
this
in your each()
callback body should be changed to $(this)
:
$(".test").each(function(){
var theNum = parseInt($(this).html())+1 || 0;
$(this).html(theNum);
});
see this demo.
回答3:
it is applying the first instance of .test
to all of them. You need to loop through all of the elements and apply a +1
separately.
$('.test').each(function(){
$(this).html(parseInt($(this).html())+1)
});
回答4:
you need to use $(this) instead this .I have updated the code http://jsfiddle.net/DTyY7/6/ .Hope it helps
回答5:
$(document).ready(function(){
function change(){
$(".test").each(function(i, domElement){
//var theNum = parseInt(this.html())+1;
var num = parseInt($(".test").html());
num++
$(".test").html(num);
});
//this works... the other one doesnt why?!?!
/* var theNum = parseInt($(".test").html())+1;
$(".test").html(theNum);
*/}
setInterval(change,1000);
});
This is how you can fix it. Because you are in another scope the keword this doesn't work.
回答6:
$(document).ready(function() {
function change() {
$(".test").each(function(i,domeElement) {
var theNum = parseInt($(this).html())+1;
$(this).html(theNum);
});
}
setInterval(change,1000);
});
来源:https://stackoverflow.com/questions/8490290/jquery-each-selector-doesnt-work