【问题标题】:Element doesn't appear when appended in D3元素在 D3 中附加时不出现
【发布时间】:2016-03-25 21:29:08
【问题描述】:

我正在尝试创建一个显示颜色块的图例、与该颜色对应的名称以及用于更改颜色的下拉列表。这是我的代码:

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; });      

}

颜色和文字出现,但下拉元素不出现。

更新:好的,我尝试执行以下操作,但它给了我错误“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; });'

【问题讨论】:

  • 好的,我读了。这是否意味着我正在尝试做的事情是不可能的?还是可能?从那个链接真的不清楚......
  • .在附加之后和之前(无效
  • OK 错误消失了,仍然没有。想法?

标签: javascript html css d3.js


【解决方案1】:

在 SVG 中,html 元素只能是 foreignObject 元素的子元素,而 foreignObject 元素不能是文本元素的子元素。 foreignObject 元素可以是文本元素的兄弟,因此您的 DOM 需要看起来像这样。

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

【讨论】:

    【解决方案2】:

    对于异物,您应该像这样附加元素: .append("xhtml:div") 而不是 .append("div")

    更正完整的 sn-p。

     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; } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-05
      • 1970-01-01
      • 1970-01-01
      • 2015-02-17
      • 2014-03-10
      • 1970-01-01
      相关资源
      最近更新 更多