Wie kann ich mit D3 (oder javascript), um eine form option als "selected"

Ich versuche zu lernen D3. Ist es elegante eine Möglichkeit, die Suche durch alle Optionen in einem select-Formular-element, und geben Sie eine option mit einem entsprechenden Wert als "ausgewählt"?

var xStat = "G";

var statOptions = {
    "Points": "PTS",
    "Goals": "G",
    "Assists": "A",
    "Penalty Minutes": "PIM"
};

//create the select element
var selectUI = d3.select("#horse").append("form").append("select");

//create the options
selectUI.selectAll("option").data(d3.keys(statOptions)).enter().append("option").text(function(d) {
    return d;
});

//add values to the options
selectUI.selectAll("option").data(d3.values(statOptions)).attr("value", function(d) {
    return d;
});


//create a func to check if the value of an option equals the xStat var
//if yes, set the attribute "selected" to "selected"
var checkOption = function(e, i, a) {
    if (e[i]["value"] === xStat) {
        return e[i].attr("selected", "selected");
    }
};

//selectUI.selectAll("option").forEach(checkOption);
selectUI.selectAll("option").call(checkOption);​

Habe ich meinen nicht funktionierenden Versuch zu tun, diese hier:
http://jsfiddle.net/sspboyd/LzrAC/2/

Dank.

  • Was genau meinst du mit elegant?
  • Ich habe bearbeitet die ursprüngliche Frage zu löschen, 'elegant'. Ich war nicht bewusst, dass das Wort eleganten hatten einen Einfluss auf das problem zu verstehen ich versuche zu verstehen. danke.
InformationsquelleAutor sspboyd | 2012-10-27
Schreibe einen Kommentar