gpt4 book ai didi

How to get random background colors on a select2 tags?(如何在选定的2个标签上获得随机的背景颜色?)

转载 作者:bug小助手 更新时间:2023-10-28 11:34:20 25 4
gpt4 key购买 nike



I would like to have multiple tags with different colors on a select2.

我想有多个标签上的不同颜色的选择2。


It can be done with

这件事可以用


$('#select2Skills').select2({
tags: true,
multiple: true,
allowClear: true,
placeholder: 'Add a skill, a keyword, a sentence.',
templateSelection: function(d, container) {
$(container).css({ "background-color": randomHSL() });
return d.text;
}
});

but then each time I enter a new tag, all colors for existing tags are changed.
How do I prevent this ? By adding a attribut “colored” ?

但每次我输入一个新标记时,现有标记的所有颜色都会更改。我如何防止这种情况发生?通过添加一个属性,但“有色”?


Any help welcomed.

欢迎任何帮助。


更多回答
优秀答案推荐

To prevent the color of existing tags from changing when you add a new tag in Select2 with different colors, you can store the colors of the existing tags and then assign them consistently each time a new tag is added. You can use a data attribute to store the color for each option and then retrieve it when needed.

为了防止在Select2中添加具有不同颜色的新标签时现有标签的颜色发生变化,您可以存储现有标签的颜色,然后在每次添加新标签时一致地分配它们。您可以使用数据属性来存储每个选项的颜色,然后在需要时检索它。


Here's how you can modify your code to achieve this:

以下是修改代码以实现这一点的方法:


// Initialize Select2 with tags and multiple options

//使用标签和多个选项初始化Select2


$('#select2Skills').select2({
tags: true,
multiple: true,
allowClear: true,
placeholder: 'Add a skill, a keyword, a sentence.',
templateSelection: function (d, container) {
var color = $(d.element).data('color'); // Retrieve the color from data attribute

if (!color) {
color = randomHSL(); // Generate a random color if it doesn't exist
$(d.element).data('color', color); // Store the color in data attribute
}

$(container).css({ "background-color": color });
return d.text;
}});

In this code:

在此代码中:



  1. When a new tag is added, it checks if the data attribute data-color exists for that tag. If it does, it retrieves the color from it. If it doesn't, it generates a random color using the randomHSL() function (you may have your own color generation function).



  2. The color is then stored in the data-color attribute of the option element so that it can be retrieved and used consistently when rendering the tag.




This way, existing tags will retain their colors, and new tags will be assigned colors as needed without affecting the existing ones.

这样,现有标签将保留其颜色,并且将根据需要为新标签指定颜色,而不会影响现有标签。


更多回答

Yes. Perfect. Many thnks for the clear explanations on your answer. I have used $(d).attr('color'); instead of $(d.element).data('color'); and $(d).attr('color', color); instead of $(d.element).data('color', color);

是。完美无缺。谢谢你对你答案的清楚解释。我使用了$(D).attr(‘COLOR’);而不是$(d.Element).Data(‘COLOR’);和$(D).attr(‘COLOR’,COLOR);而不是$(d.Element).Data(‘COLOR’,COLOR);

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