根据JSON中的颜色值更改div的颜色

时间:2013-10-23 00:16:27

标签: javascript jquery json

鉴于以下代码,我需要将“header”div的颜色更改为相应JSON中的颜色。使用:

$("#dropdown").change(function() {
$("#header").css("background-color", $(this).val());
}).change(); 

如何获取JSON中的十六进制颜色并将其应用于div?

HTML

<div id="header">Header</div>
<select id="dropdown">
<option value="">Select</option>
</select>
<a href="#" id="fetch">Fetch JSON</a>

JSON

var json = {
"dropdown": [
{
    "optionText": "Budget Starter",
    "headerText": "Work 1-on-1 with your expert to build new spending habits (and break some old ones). Get on a real, sustainable budget that fits your lifestyle.",
    "color": "#59c5c7"
},
{
    "optionText": "5 Year Planner",
    "headerText": "Declare what you want - freedom from debt, security for your family, or an amazing trip. Your expert will build you a custom plan to help you get there.",
    "color": "#009cd0"
},
{
   "optionText": "Portfolio Builder",
    "headerText": "Start training for the world's hardest game: investing. Your expert will help you grow into a disciplined and balanced portfolio manager.",
    "color": "#39ad74"
}
]
};

的jQuery

$('#fetch').click(function() {
$.post('/echo/json/', {json: JSON.stringify(json)}, function(data) {
    $.each(data.dropdown, function(i, v) {
        $('#dropdown').append('<option value="' + v.optionText + '">' + v.optionText +     
'</option>');
    });
});
});
//change color of header container based on dropdown selection
$("#dropdown").change(function() {
$("#header").css("background-color", $(this).val());
}).change();

1 个答案:

答案 0 :(得分:1)

嗯,将颜色设置为值而不是文本。

<option value="' + v.optionText + '">

<option value="' + v.color+ '">

如果您需要将值作为文本,请使用数据属性。

相关问题