简体   繁体   中英

Element doesn't appear when appended in D3

I'm trying to create a legend that shows a color block, the name corresponding to that color, and a dropdown to change the color. Here is my code:

function create_legend(){
    var legend = legendSVG.selectAll("g.legend")
    .data(ext_color_domain)
    .enter().append("g")
    .attr("class", "legend");

    var ls_w = 20, ls_h = 20;

    //create color blocks
    legend.append("rect")
    .attr("x", 20)
    .attr("y", function(d, i){ return height - (i*ls_h) - 2*ls_h;})
    .attr("width", ls_w)
    .attr("height", ls_h)
    .style("fill", function(d, i) { return color_scale[i]; })
    .style("opacity", 0.8);

    //create text
    legend.append("text")
    .attr("x", 50)
    .attr("y", function(d, i){ return height - (i*ls_h) - ls_h - 4;})
    .text(function(d, i){ return segment_map[i]; });

    //create dropdown for colors
    legend.append("div")
    .append("select")
    .attr("x", 80)
    .attr("y", function(d, i){ return height - (i*ls_h) - ls_h - 4;})
    .selectAll("option")
    .data(color_names)
    .enter().append("option")
    .attr("value", function (d) { return d; })
    .text(function (d) { return d; });      

}

The color & text appears, but the dropdown element does not.

在此输入图像描述

Update: Ok, I tried doing the following but it gives me the error "Uncaught SyntaxError: Unexpected token"

'//create dropdown for colors
    legend.append("foreignObject")
    .attr("class", ".dropdown")
    .append("div")
    .append("select")
    .attr("x", 80)
    .attr("y", function(d, i){ return height - (i*ls_h) - ls_h - 4;})
    .selectAll("option")
    .data(color_names)
    .enter().append("option")
    .attr("value", function (d) { return d; })
    .text(function (d) { return d; });'

In SVG a html element can only be the child of a foreignObject element and a foreignObject element cannot be the child of a text element. A foreignObject element can be the sibling of a text element though so your DOM needs to look something like this.

g
|-   rect
|-   text
|-   foreignObject
        |- div

For foreign object you should be appending the element like this: .append("xhtml:div") instead of .append("div")

corrected full snippet.

 legend.append("foreignObject")
    .attr("class", ".dropdown")
    .append("xhtml:div")
    .append("xhtml:select")
    .attr("width", 80)

    .attr("x",function(d, i){ return width * i})
    .attr("y", function(d, i){ return height - (i*ls_h) - ls_h - 4;})
    .selectAll("option")
     .data(color_names)
    .enter().append("xhtml:option")
    .attr("value", function (d) { return d; })
    .text(function (d) { return d; } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM