我可以在构造函数中放置一个jquery处理程序吗?

时间:2011-07-15 04:00:22

标签: javascript jquery

我看到我是否可以制作一些面向对象的javascript,并且我有以下代码。

当我将我的jquery事件处理程序移动到构造函数中时,我感到困惑,因为现在我有两个这个变量......

我接近这个错误还是有办法让它起作用?

function Dropdown(ddlname) {
    this.Value = 0;
    this.Selected = false;
    this.DDL = ddlname;
    this.Limited = false;
    this.SelectLast = function () {
        $(this.DDL + ' option:last').attr('selected', 'selected');
    }
    $(ddlname).change(function () {
        var v = $(this).val(); // <== ? 
        if (typeof v == 'number') {
            this.Value = v; // <== ?
            this.Selected = true; // <== ? 
        }
    });
    return true;
};

3 个答案:

答案 0 :(得分:3)

您需要将构造函数的上下文中的“this”赋给局部变量,以便能够在jquery事件处理程序中引用它。

function Dropdown(ddlname) {
    this.Value = 0;
    this.Selected = false;
    this.DDL = ddlname;
    this.Limited = false;
    var hold = this;
    this.SelectLast = function () {
        $(hold.DDL + ' option:last').attr('selected', 'selected');
    }
    $(ddlname).change(function () {
        var v = $(this).val(); // <== ? 
        if (typeof v == 'number') {
            hold.Value = v; // <== ?
            hold.Selected = true; // <== ? 
        }
    });
    return true;
};

答案 1 :(得分:2)

我从微软的DataJS团队的Marcelo Ruiz那里学到的一个技巧如下:

function Dropdown(ddlname) 
{    
    var that = this;
    //rest of your code. now there is no confusion of this since you have that :) 
};

不确定这是否会对您有所帮助。但这只是我学到的一招。

答案 2 :(得分:0)

是的,您可以,但您需要在文档就绪功能中调用该类。我很确定这是不好的做法。

您应该考虑将$传递给构造函数或创建jQuery扩展。

相关问题