开发者

How to pass arguments to an event handler?

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);

    }
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜