我正在创建一个包含颜色样本的侧边栏,单击该样本时,用这些颜色填充表单。它用于Wordpress主题。
每个颜色样本都是包含在数组中的对象。我在数组上使用.each()函数为每个样本创建HTML,但我还需要创建一种方法,以便在单击样本时,颜色字段将填充该样本的颜色。
这是小提琴:http://jsfiddle.net/ccnokes/6emfD/ *代码中有更多评论可以澄清我在说什么。
从小提琴中可以看出,每个样本只用最后一个样本的颜色填充字段。 :(
答案 0 :(得分:0)
稍微重新组织它,以便在创建时而不是之后将click事件附加到每个锚标记。
//Color Swatches JS
//color swatch array containing objects that contain the target fields and colors
var swatches = [
$fuego = {
name: 'fuego',
primary_color: '#c0342a',
primary_hover_color: '#a0140a',
primary_hover_color_2: '#800000',
secondary_color: '#ff7600',
secondary_hover_color: '#df5600',
secondary_hover_color_2: '#bf3600',
tertiary_color: '#ffd005',
tertiary_color2: '#ffd409',
h1_color: '#c0342a',
h2_color: '#a0140a',
background_color: '#ffd005'},
$veggies = {
name: 'veggies',
primary_color: '#5f8a42',
primary_hover_color: '#86ad59',
primary_hover_color_2: '#f6faa1',
secondary_color: '#f28410',
secondary_hover_color: '#d66011',
secondary_hover_color_2: '#b24400',
tertiary_color: '#a44a0e',
tertiary_color2: '#a84e0f',
background_color: '#a44a0e'},
$jazz = {
name: 'jazz',
primary_color: '#3b2e8c',
primary_hover_color: '#022859',
primary_hover_color_2: '#023059',
secondary_color: '#6cafd9',
secondary_hover_color: '#4c8fb9',
secondary_hover_color_2: '#2c6f99',
tertiary_color: '#ffffff',
tertiary_color2: '#fcfcfc',
background_color: '#ffffff'}
];
//Create color swatches HTML
$(swatches).each(function() {
var $swatch = this;
$('<a id="' + this.name + '"><ul class="swatch"><li class="main" style="background-color:' + this.primary_color + '"></li><li style="background-color:' + this.primary_hover_color + '"></li><li style="background-color:' + this.primary_hover_color_2 + '"></li><li class="main" style="background-color:' + this.secondary_color + '"></li><li style="background-color:' + this.secondary_hover_color + '"></li><li style="background-color:' + this.secondary_hover_color_2 + '"></li></ul></a>').on('click', function() {
fillSwatches($swatch);
console.log($swatch);
}).appendTo('.swatch-wrap');
});
//on swatch click, fill fields with corresponding colors
function fillSwatches($swatch) {
$.each($swatch, function($key, $value) {
fillColor($key, $value);
});
}
//fill color scheme
function fillColor($field, $color) {
$('#' + $field).val($color).css("background-color", $color).change();
}
/*the following function works but can't it be abstracted so that every swatch doesn't have to be written out in this format? */
/*
$('#fuego').on( 'click', function(){
fillSwatches($fuego);
});
*/
答案 1 :(得分:0)
为每个<a>
添加一个swatch data-attr,然后执行以下操作:
$('a').on('click', function(){
var swatch = swatches[$(this).data('swatch')];
fillSwatches(swatch);
});