Получить все те же классы из существующего тега "g" - PullRequest
0 голосов
/ 18 сентября 2018

Я получил svg, который был задан как тег с большим количеством разных тегов (text и tspan). Я просто хочу попытаться получить все имена классов, которые названы "aftertext". Я пробовал это, но я ничего не получаю ..

svg - это тег g в svg. :

function add_total_svg(svg) {
    var all_aftertext = svg.selectAll(".aftertext");
}

Вот мой код:

var margin = {top: 30, right: 20, bottom: 30, left: 20},
    width = 400,
    barHeight = 20,
    barWidth = (width - margin.left - margin.right) * 0.8;

var i = 0,
    duration = 0,
    root;

var path = [];
path[0] = {"attributes": "DPGF", "children": [{"attributes": "LOT:  nom 13.CVC", "children": [{"attributes": "Tous_DPGF:  Profondeur 1", "children": [{"attributes": "Poste:  Rang Rang 1 | 100509", "children": [{"attributes":"Debut_poste_Excel | 0.0"}, {"attributes":"Fin_poste_Excel | 19.0"}, {"attributes":"Mot_cle debut"}, {"attributes":"Rang Rang 1"}]}, {"attributes": "Poste:  Rang Rang 1 |     40", "children": [{"attributes":"Debut_poste_Excel | 20.0"}, {"attributes":"Fin_poste_Excel | 20.0"}, {"attributes":"Mot_cle chauffage"}, {"attributes":"Rang Rang 1"}]}, {"attributes": "Poste:  Rang Rang 1 |     44", "children": [{"attributes":"Debut_poste_Excel | 21.0"},
{"attributes":"Fin_poste_Excel | 23.0"}, {"attributes":"Mot_cle Préambule"}, {"attributes":"Rang Rang 1"}]}, {"attributes": "Poste:  Rang Rang 1 |     49", "children": [{"attributes":"Debut_poste_Excel | 24.0"}, {"attributes":"Fin_poste_Excel |25.0"}, {"attributes":"Mot_cle Préambule"}, {"attributes":"Rang Rang 1"}]}, {"attributes": "Poste:  Rang Rang 1 |     53", "children": [{"attributes":"Debut_poste_Excel |26.0"}, {"attributes":"Fin_poste_Excel |27.0"}, {"attributes":"Mot_cle production thermique"}, {"attributes":"Rang Rang 1"}]}, {"attributes": "Poste:  Rang Rang 1 |     93", "children": [{"attributes":"Debut_poste_Excel | 28.0"}, {"attributes":"Fin_poste_Excel | 65.0"}, {"attributes":"Mot_cle chauffage"}, {"attributes":"Rang Rang 1"}, {"attributes": "Tous_DPGF:  Profondeur 2", "children": [{"attributes": "Poste:  Rang Rang 2", "children": [{"attributes":"Debut_poste_Excel | 31.0"}, {"attributes":"Fin_poste_Excel | 65.0"}, {"attributes":"Mot_cle Échangeur"}, {"attributes":"Rang Rang 2"}, {"attributes": "Tous_DPGF:  Profondeur 3", "children": [{"attributes": "Poste:  Rang Rang 4", "children": [{"attributes":"Debut_poste_Excel | 35.0"}, {"attributes":"Fin_poste_Excel| 35.0"},
{"attributes":"Mot_cle Manchon"}, {"attributes":"Rang Rang 4"}]}, {"attributes": "Poste:  Rang Rang 4", "children": [{"attributes":"Debut_poste_Excel |36.0"}, {"attributes":"Fin_poste_Excel |36.0"}, {"attributes":"Mot_cle Vanne"}, {"attributes":"Rang Rang 4"}]}, {"attributes": "Poste:  Rang Rang 4", "children": [{"attributes":"Debut_poste_Excel| 37.0"}, {"attributes":"Fin_poste_Excel |37.0"}, {"attributes":"Mot_cle Thermomètre"}, {"attributes":"Rang Rang 4"}]}, {"attributes": "Poste:  Rang Rang 4", "children": [{"attributes":"Debut_poste_Excel    | 38.0"}, {"attributes":"Fin_poste_Excel| 38.0"}, {"attributes":"Mot_cle Sonde"}, {"attributes":"Rang Rang 4"}]}, {"attributes": "Poste:  Rang Rang 4", "children": [{"attributes":"Debut_poste_Excel  |39.0"}, {"attributes":"Fin_poste_Excel   |39.0"}, {"attributes":"Mot_cle Soupape"}, {"attributes":"Rang Rang 4"}]}, {"attributes": "Poste:  Rang Rang 4", "children": [{"attributes":"Debut_poste_Excel | 40.0"}, {"attributes":"Fin_poste_Excel |41.0"}, {"attributes":"Mot_cle Pressostat"}, {"attributes":"Rang Rang 4"}]}, {"attributes": "Poste:  Rang Rang 4", "children": [{"attributes":"Debut_poste_Excel             | 42.0"}]}]}]}]}]}]}]}]};

var value = [];
create_a_tree_obj(path);

   

 function add_total_svg(svg, globaldiv, cell) {
        var all_number = svg.selectAll('.node tspan.aftertext')
    .each(function (d) {
        console.log(d);
    });
    cell.attr("class", "total").attr("id", "total");
    cell.select("#title").text("Total");
    }

function create_a_tree_obj(path) {
    var i = 0;
    var div;
    var cell;
    var svg_array = [];
    
    if (i === 0) {
        div = d3.select("body").append("div")
            .attr("id", "div");
    }
    for (i ; path[i]; i++) {
        cell = div.append("div").attr("class", "cell").attr("id", "cell");
        svg_array[i] = cell.append("svg")
        .attr("id", "" + i)
        .attr("width", 600) // + margin.left + margin.right)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
        add_the_tree_graph(svg_array, path, i);
    }
    add_total_svg(svg_array[i - 1], div);
}

function add_the_tree_graph(svg_array, path, i) {
    var root = [];
    
//    d3.json(path[i], function(error, json) {
//        if (error) throw error;
        for (; path[i]; i++) { 
            root[i] = d3.hierarchy(path[i]);
            root[i].x0 = 0;
            root[i].y0 = 0;
            update(root[i], svg_array[i], "" + i, root);
        }
//    });
}    

function update(source, svg_var, svg_id, all_sources) {

  // Compute the flattened node list.
    var nodes = source.descendants();
    var height = Math.max(500, nodes.length * barHeight + margin.top + margin.bottom);

    document.getElementById(svg_id).setAttribute("height", height);

  d3.select(self.frameElement).transition()
      .duration(duration)
      .style("height", height + "px");

  // Compute the "layout". TODO https://github.com/d3/d3-hierarchy/issues/67
  var index = -1;
  source.eachBefore(function(n) {
    n.x = ++index * barHeight;
    n.y = n.depth * 20;
  });

  // Update the nodes…
  var node = svg_var.selectAll(".node")
    .data(nodes, function(d) { return d.id || (d.id = ++i); });

  var nodeEnter = node.enter().append("g")
      .attr("class", "node")
      .attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; })
      .style("opacity", 0);

  // Enter any new nodes at the parent's previous position.
  nodeEnter.append("rect")
      .attr("y", -barHeight / 2)
      .attr("height", barHeight)
      .attr("width", barWidth)
      .style("fill", color)
      .on("click", function(d, e) {
      if (d.children) {
            d._children = d.children;
            d.children = null;
      } else {
        d.children = d._children;
        d._children = null;
      }
      update(source, svg_var, svg_id, all_sources); //recursion pour re-afficher la page dynamiquement.
    });
    nodeEnter.append("text")
    .attr("dy", 3.5)
    .attr("dx", 5.5)
    .each(function (d) {
    if(d.data.attributes.indexOf('|') > -1) {
        var beforeText = d.data.attributes.substr(0,   d.data.attributes.indexOf('|')).trim(),
        afterText = d.data.attributes.substr(d.data.attributes.indexOf('|')+1, d.data.attributes.length).trim();

        d3.select(this).append('tspan').classed('beforetext', true).text(beforeText);
        var afterTextSpan = d3.select(this).append('tspan').classed('aftertext', true).text(afterText);

    // position aftertext
        var temp_text = svg_var.append('text').classed('temp_text', true).text(afterText);
        afterTextSpan.attr('x', (288 - afterText.length * 6) - 5)
        temp_text.remove();
    } else {
        d3.select(this).text(d.data.attributes); 
    }
  });

  // Transition nodes to their new position.
    nodeEnter.transition()
      .duration(duration)
      .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })
      .style("opacity", 1);
    node.transition()
      .duration(duration)
      .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })
      .style("opacity", 1)
    .select("rect")
      .style("fill", color);

  // Transition exiting nodes to the parent's new position.
  node.exit().transition()
      .duration(duration)
      .attr("transform", function(d) { return "translate(" + source.y + "," + source.x + ")"; })
      .style("opacity", 0)
      .remove();
}

//setTimeout(() => simulateClick(240, 141), 2000); //Click test worked
function color(d) {
  return d._children ? "#3182bd" : d.children ? "#c6dbef" : "#fd8d3c";
}
.node rect {
  cursor: pointer;
  fill: #fff;
  fill-opacity: 0.5;
  stroke: #3182bd;
  stroke-width: 1.5px;
}

#div { display: table-row; }
#div .cell { display: table-cell; vertical-align: top;}
    
.node text {
  font: 10px sans-serif;
  pointer-events: none;
}

.link {
  fill: none;
  stroke: #9ecae1;
  stroke-width: 1.5px;
}
<script src="https://d3js.org/d3.v4.min.js"></script>

Мне нужно только получить в массиве все классы, которые названы "aftertext" (синий прямоугольник с номером).

1 Ответ

0 голосов
/ 18 сентября 2018

Чувак, в комментариях столько путаницы. Вот оригинальный пост , откуда последующий текст входит в картину. Я ответил на этот вопрос и добавил aftertext tspan s.

@ zahreddine - я понимаю, что вы пытаетесь улучшить свой английский, но разработчикам, добавившим комментарии, было бы легче понять проблему, если бы вы обратились к исходному сообщению и упомянули tspan s добавлены в ответ, и вам просто нужно получить эти tspan s. Во всяком случае, в следующий раз.

Переходя к решению, вот один из подходов для выбора всех tspan на основе aftertext class:

// printing all after-texts
svg_var.selectAll('.node:not(.child) tspan.aftertext')
 .each(function (d) {
    console.log(d);
 });

А что касается класса child в вышеприведенном коде, он вытекает из этого дополнения, которое должно различать дочерние и родительские узлы (как вы говорите, вы ищете только blue rects, но если вы ищете ВСЕ посттексты, просто уберите селектор :not(.child)):

var nodeEnter = node.enter().append("g")
 .attr("class", function (d) {
   return 'node ' + (d.children ? '' : 'child'); 
 })

Используя вышеприведенные изменения, вот вилка Plunkr (проверьте консоль на наличие желаемого выхода):

https://plnkr.co/edit/VSegZNp9uGkNj5VvLBAY?p=preview

Я вижу, что вы пытаетесь суммировать эти восстановленные значения, теперь это должно быть проще. Если вы не можете этого сделать, создайте новый вопрос и вставьте либо код, либо ответвление вашего Plunkr.

Надеюсь, это поможет.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...