0

我正在尝试根据用户选择的选项从 JSON 中提取 headerText,并让它填充我的代码的结果 div。我可以拉出十六进制颜色并更改框背景,但无法取出 headerText。有任何想法吗?

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'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) {
        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).data('header'));
}).change();

CSS:

#result {
    height: 50px;
}
#dropdown, #fetch {
    position: relative; 
    left: 50%; 
    margin: 0 auto;
}
4

2 回答 2

1

只需用这个逻辑替换下拉更改代码。它会为你工作

$("#dropdown").change(function () {
    $("#result").css("background-color", $(this).val());
    $("#result").html($(this).find("option:selected").data("header"));
}).change();
于 2013-10-23T14:42:04.323 回答
1

这应该有效。问题出在

$("#result").css("background-color", $(this).val()).text(
   $(this).data('header')  // <--
);

$(this) 在这种情况下是一个选择,而不是选定的选项。

//change color of header container based on dropdown selection
$("#dropdown").change(function() {
    var headerText = $('option:selected', this).data('header');
    $("#result").css("background-color", $(this).val()).text(headerText);
}).change();
于 2013-10-23T14:39:51.773 回答