gpt4 book ai didi

jquery - 将事件附加到数组中的对象

转载 作者:行者123 更新时间:2023-12-01 05:59:47 24 4
gpt4 key购买 nike

我正在创建一个包含颜色样本的侧边栏,单击该侧边栏时,会用这些颜色填充表单。它适用于 WordPress 主题。

每个颜色样本都是包含在数组中的一个对象。我在数组上使用 .each() 函数为每个样本创建 HTML,但我还需要创建一种方法,以便在单击样本时,颜色字段会填充该样本的颜色。

这是 fiddle :http://jsfiddle.net/ccnokes/6emfD/*代码中有更多注释可以澄清我在说什么。

正如您从 fiddle 中可以看出的那样,每个样本仅用最后一个样本的颜色填充字段。 :(

最佳答案

稍微重新组织一下,以便在每个 anchor 标记创建时(而不是创建之后)将点击事件附加到每个 anchor 标记。

http://jsfiddle.net/6emfD/2/

//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);
});
*/​

关于jquery - 将事件附加到数组中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12394553/

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