jQuery Function don't work with two elements
My jQuery script don't return the number in ascending order.
jQuery
$(document).ready(function() {
$.xpto = function(dom, speed) {
i = 0;
interval = setInterval(function() {
i++;
$(dom).append(i + '<br>');
}, speed);
};
$.xpto('#a', 1000);
$.xpto('#b', 2000);
});
And my HTML:
<div id="a" style="background:blue;float:left;"></div&开发者_如何学Gogt;
<div id="b" style="background:red;float:left;"></div>
Thanks!
You're missing the var
keyword before i = 0
and interval
. This causes all instances of function $.xpto
to share these variables. Furthermore, the i
variable resets to zero each time you call $.xpto
.
According to your function's logic, this should happen:
a 1
b 2
a 3
a 4
a 5
b 6
a 7
a 8
b 9
...
If this is not as expected, mention your wishes, and I will have a look at it.
Try this: - http://jsfiddle.net/FloydPink/hWYG5/
$(document).ready(function() {
$.xpto = function(dom, speed) {
var i = 0;
interval = setInterval(function() {
i++;
$(dom).append(i + '<br>');
}, speed);
};
$.xpto('#a', 1000);
$.xpto('#b', 2000);
});
Without the var
keyword, the variable i is not getting declared explicitly within the closure and is being reused within both the calls to $.xpto
If you are trying to give each row its own count variable then you must use the var keyword before defining i.
http://jsfiddle.net/pF2ef/2/
精彩评论