Учитывая мой JSON файл, я хочу отобразить значение headerText в div результатов, когда пользователь выбирает данную опцию из выпадающего меню, предоставленного JSON:
HTML
<div id="result"></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 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.color + '">' + v.optionText + '</option>');
});
});
});
//change color of header container based on dropdown selection
$("#dropdown").change(function() {
$("#result").css("background-color", $(this).val());
}).change();
CSS
#result{height: 50px;}
Поскольку вы используете jQuery, вы можете реализовать это с помощью API данных. Он позволяет хранить произвольные объекты вместе с элементами DOM.
Измененный jQuery (см. Скрипку здесь)
$('#fetch').click(function() {
$.post('/echo/json/', {json: JSON.stringify(json)}, function(data) {
var dropdown = $('#dropdown');
$.each(data.dropdown, function(i, v) {
var option = $('<option value="' + v.color + '">' + v.optionText + '</option>');
option.data('header', v.headerText).appendTo(dropdown);
});
});
});
//change color of header container based on dropdown selection
$("#dropdown").change(function() {
$("#result").css("background-color", $(this).val()).text($(this).find('option:selected').data('header'));
}).change();
.text($(this).data('header'))
не дает мне headerText
$('#dropdown').append('<option value="' + v.color + '">' + v.optionText + '</option>');
try$('#dropdown').append($('<option value="' + v.color + '">' + v.optionText + '</option>'));