var MyObject = {
init: function () {
this.items = $('#menu a');
for (var i = 0; i < this.items.length; i++) {
$(this.items[i]).bind('click', this.doSomething);
}
},
doSomething: function (index) {
alert(this.items[index].innerHTML);
开发者_如何转开发 // alerts: One, Two, Three
}
};
I need pass the index (i)
Edit: Illustration: http://jsfiddle.net/mUjAj/
There's no need to pass an index here, since this
will refer to the element you want clicked inside a click
event handler, you can just do this:
var MyObject = {
init: function () {
this.items = $('#menu a');
this.items.bind('click', this.doSomething);
},
doSomething: function () {
alert(this.innerHTML);
}
};
You can test it out here.
Try this and see if it works:
var MyObject = {
init: function () {
this.items = $('#menu a');
for (var i = 0; i < this.items.length; i++) {
$(this.items[i]).bind('click', {index:i}, this.doSomething);
}
},
doSomething: function (e) {
alert(e.data.index);
}
};
精彩评论