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)
答案 0 :(得分:1)
这里不需要传递索引,因为this
将引用您想要在click
事件处理程序中单击的元素,您可以这样做:
var MyObject = {
init: function () {
this.items = $('#menu a');
this.items.bind('click', this.doSomething);
},
doSomething: function () {
alert(this.innerHTML);
}
};
答案 1 :(得分:0)
试试这个,看它是否有效:
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);
}
};