如何将参数传递给事件处理程序?

时间:2010-10-29 01:23:33

标签: parameter-passing jquery

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)

修改:插图:http://jsfiddle.net/mUjAj/

2 个答案:

答案 0 :(得分:1)

这里不需要传递索引,因为this将引用您想要在click事件处理程序中单击的元素,您可以这样做:

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

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

    }
};