为for循环中的选项提供颜色

时间:2019-01-13 15:23:26

标签: javascript c# jquery

在获得ajax成功的时候,我有4个值value.BookableResourceId,value.Name,value.FontColor,value.BackgroundColor。我的要求是在创建具有名称和BookableResourceId的选项时添加FontColor和BackgroundColor,以显示具有相应字体和背景色的项目。

$(resourceElement).select2({
    data: resourceData,
    closeOnSelect: true,
    placeholder: '(Empty)',
    allowClear: true,
}).on('select2:open', function (e) { 
        $.ajax({
            url: '/XX/YYY',
            type: "POST",
            async: false,
            success: function (response) {
                  for (var data in response) {                    
                      var newOption = new Option(response[data].Name, response[data].BookableResourceId, false, false);                                          
                      $(resourceElement).append(newOption).trigger('change');  
                  }

下面显示了ajax响应:

enter image description here

我尝试了以下代码。但是它也无法进行数据填充。

var add_Helpresrs = [];
$.each(response, function (index, value) {
                        add_Helpresrs.push(
                            {
                                id: value.BookableResourceId,
                                text: value.Name,
                                color: value.FontColor,
                                background: value.BackgroundColor
                            });
                    });

var newArray = [];
add_Helpresrs.map(function (item) {
                        newArray.push({
                            id: item.id,
                            text: '<span style="color:' + item.color + '; background:' + item.background + '">' + item.text + '</span>'
                        })
                    })
$(resourceElement).append(newArray).trigger('change');

1 个答案:

答案 0 :(得分:0)

只需将颜色和背景色添加到响应中的新选项中即可:

const response = [{
  Name: 'bob',
  BookableResourceId: 'bob\'s book',
  FontColor: 'red',
  BackgroundColor: 'blue'
}, {
  Name: 'Steve',
  BookableResourceId: 'steve\'s book',
  FontColor: 'green',
  BackgroundColor: 'orange'
}];

const select = document.querySelector('select');

response.forEach(book => {
  var newOption = new Option(book.Name, book.BookableResourceId, false, false);

  newOption.style.color = book.FontColor;
  newOption.style.backgroundColor = book.BackgroundColor;

  select.appendChild(newOption);
});
<select>
  <option>-----</option>
</select>