I create one object named “Ball”.
after document load, script will create 12 instance of object and insert so many element li to
<ul></ul>
my purpose is that when click ball, it show index of ball.
for exmaple: click No 3 ball, it show 3.
but when i click each ball, it always show 12.
sorry, i cannot upload snapshot for html document, since i am new guy here.
function Ball(idx, parent, libra) {
this.idx = idx;
this.parent = parent;
this.libra = libra;
this.init();
}
Ball.r = 30;
Ball.prototype = {
init: function() {
var _html = $("<li><div class='ball'><span>" + this.idx + "</span></div></li>"),
pos
_this = this;
this.parent.append(_html);
this.html = _html.find(".ball");
this.html.css({
height: Ball.r * 2 + "px",
width: Ball.r * 2 + "px",
lineHeight: Ball.r * 2 + "px"
});
pos = this.html.position()
this.html.css({
left: pos.left + "px",
top: pos.top + "px",
position: "absolute"
});
this.html.mousedown(function() {alert(_this.idx)});
}
};
$("document").ready(function() {
var parent = $("#balls ul"),
libra = 1;
for (var i = 1; i < 13; i++) {
new Ball(i, parent, libra)
}
});
You are missing a comma so
_thisis global.Since it is global, you are getting the value of the last Ball created.
The solution:
Add the missing comma.