Luistar15
Luistar15

Reputation: 1729

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/

Upvotes: 1

Views: 320

Answers (2)

Nick Craver
Nick Craver

Reputation: 630429

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.

Upvotes: 1

Phil.Wheeler
Phil.Wheeler

Reputation: 16848

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

    }
};

Upvotes: 0

Related Questions