$(this)无法正常工作

7

我正在使用ColorPicker插件。我用以下代码初始化了该插件:

$(".colorpic").ColorPicker({
    color: '#0000ff',
    onShow: function (colpkr) {
        $(colpkr).fadeIn(500);
        return false;
    },
    onHide: function (colpkr) {
        $(colpkr).fadeOut(500);
        return false;
    },
    onChange: function (hsb, hex, rgb) {
        $(this).css('backgroundColor', '#' + hex);  <= $(this) not working 
    }
});

现在我的问题是,在onchange事件中,$(this)无法正常工作。请帮我解决一下?


也许你需要将 this 绑定到 onChange 上? - tkone
1
可能插件没有将其上下文传递给“onChange”方法。打开一个问题 :) - Terry
2个回答

9
尝试像这样:

试试这个:

$(".colorpic").each(function(){
    var $this = $(this);

    $this.ColorPicker({
        color: '#0000ff',
        onShow: function (colpkr) {
            $(colpkr).fadeIn(500);
            return false;
        },
        onHide: function (colpkr) {
            $(colpkr).fadeOut(500);
            return false;
        },
        onChange: function (hsb, hex, rgb) {
            $this.css('backgroundColor', '#' + hex);
        }
    });
});

3

this是一个很大的问题,因为在这种情况下,this会传递给函数,如果我没有弄错的话。 请尝试以下操作:

var colorPicker=this;
onChange: function (hsb, hex, rgb) {
    $(colorPicker).css('backgroundColor', '#' + hex); 
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接