3

我有一个像这样的小部件

$.widget("ui.myWidget", {
    //default options
    options: {
        myOptions: "test"
    },
    _create: function () {
        this.self = $(this.element[0]);
        this.self.find("thead th").click(function () {
            this.self._headerClick(); //how do I do this!!!
        });
        this.self._somethingElse();
    },
    _headerClick: function (){
    },
    _somethingElse: function (){
    },
.
.
.

该行this.self._headerClick();引发错误。这是因为在该上下文this中是被单击的th元素。如何获得对 _headerClick 函数的引用?

4

2 回答 2

6

将期望的范围存储this在变量中。

$.widget("ui.myWidget", {
    //default options
    options: {
        myOptions: "test"
    },
    _create: function () {
        var that = this; // that will be accessible to .click(...
        this.self = $(this.element[0]);
        this.self.find("thead th").click(function () {
            that._headerClick(); //how do I do this!!!
        });
        this.self._somethingElse();
    },
    _headerClick: function (){
    },
    _somethingElse: function (){
    },
于 2011-05-19T16:45:02.227 回答
2

未经测试,但可能是这样的:

_create: function () {
    var self = this,
        $elem = $(self.element[0]);

    $elem.find("thead th").click(function() {
        self._headerClick();
    });

    self._somethingElse();
},
于 2011-05-19T16:44:12.957 回答