gpt4 book ai didi

javascript - JQuery 插件 - 回调破坏了其他功能

转载 作者:行者123 更新时间:2023-11-28 01:24:25 26 4
gpt4 key购买 nike

我正在尝试构建一个基本的颜色选择器插件(主要作为学习插件开发的练习)。我有一个名为“onSelected”的回调,当您选择颜色时会触发该回调,但它破坏了插件的另一个功能(切换样本列表的可见性的能力)。

我是插件开发新手,所以我确信这是我犯的一个简单错误......

jsfiddle

插件:

(function ($) {

$.colorPicker2 = function (el, options) {


// the wrapper around the colors
var $pickerContainer = $("<div>");


// To avoid scope issues, use 'base' instead of 'this'
// to reference this class from internal events and functions.
var base = this;

// Access to jQuery and DOM versions of element
base.$el = $(el);
base.el = el;

// Add a reverse reference to the DOM object
base.$el.data("colorPicker2", base);

base.init = function () {
console.log("base.init");
base.options = $.extend({}, $.colorPicker2.defaultOptions, options);

// Put your initialization code here
// code goes here
$.each(base.options.colors, function (index, value) {

var $item = $('<div class="colorPicker-colorOption">').css({
"background-color": "#" + value
})

$item.click(function () {
console.log("item.click");

base.selectColor(value);
})

$pickerContainer.append($item);
});

//$pickerContainer.hide();
base.$el.append($pickerContainer);

if (base.options.toggleElement != null) {
base.options.toggleElement.click(function (e) {
base.togglePicker();
e.preventDefault();
});
}

};

base.togglePicker = function()
{
$pickerContainer.toggle();
}

base.selectColor = function (color) {
base.togglePicker();

if (typeof base.options.onSelected == 'function') {
base.options.onSelected.call(this, color);
}
}

// Sample Function, Uncomment to use
// base.functionName = function(paramaters){
//
// };

// Run initializer
base.init();
};

$.colorPicker2.defaultOptions = {
colors: [
'000000', '993300', '333300', '000080', '333399', '333333', '800000', 'FF6600',
'808000', '008000', '008080', '0000FF', '666699', '808080', 'FF0000', 'FF9900',
'99CC00', '339966', '33CCCC', '3366FF', '800080', '999999', 'FF00FF', 'FFCC00',
'FFFF00', '00FF00', '00FFFF', '00CCFF', '993366', 'C0C0C0', 'FF99CC', 'FFCC99',
'FFFF99', 'CCFFFF', '99CCFF', 'FFFFFF'
],

toggleElement: null,

onSelected: function (color) { }

};

$.fn.colorPicker2 = function (options) {
return this.each(function () {
(new $.colorPicker2(this, options));
});
};

})(jQuery);

如何 Hook onSelected 事件:

$(function () {
$('#primaryColorPicker').colorPicker2({
toggleElement: $('#selectPrimaryColor'),
onSelected: function (color) {
$('#selectedPrimaryColor').html("(#" + color + ")");
}
});

});

HTML:

<a id="selectPrimaryColor">Toggle Color Picker</a>
<span id="selectedPrimaryColor" />
<div id="primaryColorPicker"></div>

最佳答案

您只需学习如何编写有效的 HTML

替换

<span id="selectedPrimaryColor" />

<span id="selectedPrimaryColor"></span>

FIDDLE

关于javascript - JQuery 插件 - 回调破坏了其他功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22868564/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com