1

我正在努力实现这个 ColorPicker 插件:

http://www.eyecon.ro/colorpicker/

我有一个包含多个字段的表单,我希望在选择任何字段时弹出颜色选择器,并根据所做的选择更改值。

这是我的代码:

jQuery(function($) {
    function changeColor(e) {
        e.preventDefault();
        $(this).ColorPicker({
            onChange: function(hsb, hex, rgb) {
                $(this).attr('value', '#' + hex)
            }
        });
    }
    $('form.niceform input').live('mouseup', changeColor);
})

但是由于某种原因, $(this).attr... 部分没有识别出 $(this) 是当前选定的字段。

有人可以帮我理解我做错了什么吗?

谢谢!

4

3 回答 3

7

此时,$(this) 是颜色选择器,而不是您应用颜色选择器的元素。

尝试这样的事情:

jQuery(function($) {
    function changeColor(e) {
        e.preventDefault();
        var elem = $(this);
        elem.ColorPicker({
            onChange: function(hsb, hex, rgb) {
                elem.attr('value', '#' + hex)
            }
        });
    }
    $('form.niceform input').live('mouseup', changeColor);
})

编辑:正如 Pointy 指出的那样,您可以做几件事来使它变得更好:

jQuery(function($) {
    function changeColor(e) {
        e.preventDefault();
        var elem = $(this);
        elem.ColorPicker({
            onChange: function(hsb, hex, rgb) {
                elem.val('#' + hex)
            }
        });
    }
    $('form.niceform input').on('mouseup', changeColor);
})
于 2012-11-26T22:44:31.097 回答
1
jQuery(function($) {
    function changeColor(e) {
        e.preventDefault();

        var self = $(this);

        self.ColorPicker({
            onChange: function(hsb, hex, rgb) {
                self.val('#' + hex);
            }
        });
    }
    $('form.niceform input').live('mouseup', changeColor);
});

您应该将函数$(this)外部ColorPicker放入变量中。

于 2012-11-26T22:44:55.077 回答
0

尝试:

jQuery(function($) {
    function changeColor(e) {
        var self = this;
        e.preventDefault();
        $(self).ColorPicker({
            onChange: function(hsb, hex, rgb) {
                $(self).attr('value', '#' + hex)
            }
        });
    }
    $('form.niceform input').live('mouseup', changeColor);
})
于 2012-11-26T22:45:22.833 回答