如何在 select.options.add(new Option()) 之后添加 2 个属性

How to add 2 attributes after select.options.add(new Option())

本文关键字:之后 添加 属性 Option new select options add      更新时间:2023-09-26

我的选择菜单显示颜色名称,但使用jQueryUI (custom.iconselectmenu)我喜欢添加一个具有相应颜色的头像块。我不知道如何添加这两个属性:

data-class="avatar" data-style="background-image: none; background-color: (the rgb value)

在我的代码中:

var data = [
    { text: 'Select a Color', value: '0' },
    { text: 'Antibes Green', value: 'rgb(95,173,72)' },
    ...
    { text: 'Versailles', value: 'rgb(206,204,130)' }
];
for(var j=0; j < data.length; j++) {
    var d = data[j];
    select.options.add(new Option(d.text, d.value))
}

或者,您可以在选项上使用 setAttribute 方法,如下所示:

var option = new Option(d.text, d.value);
option.setAttribute('data-class', 'avatar');
option.setAttribute('data-style', 'background-image: none; background-color: ' + d.value);
select.options.add(option);

这里有一个小提琴:https://jsfiddle.net/ad1no8ou/

我的偏好是避免使用字符串连接创建 HTML,因为当您不可避免地忘记在连接的值中转义特殊字符时,存在错误的风险。

尝试替换此行

select.options.add(new Option(d.text, d.value))

select.innerHTML += "<option value='" + d.text + "' data-class='avatar' data-style='background-image: none; background-color: (the rgb value)'>" + d.value +"</option>";