d3.js删除节点

时间:2018-09-26 09:03:44

标签: javascript html d3.js

我有一个树状组织,当我单击“ Comparatif”树的蓝色矩形时,有时会删除一些数组(请参见Firefox上的debogger,单击蓝色矩形时会看到最后一个数组),因此在比较树上移动并擦除一些数据,但是如果我单击其他树的蓝色矩形,则不会删除任何节点,而且我也不明白为什么。

这是代码(在Firefox浏览器上尝试该代码):

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

var cursorX;
var click_mult;
var cursorY;
var svg_array = [];
var check = 0;
//stack_nb variable
var nb_data = [
    [], [], []
];
var ent = 0;
var d;

document.onmousemove = function(e) {
        cursorX = e.pageX;
        cursorY = e.pageY;
    }

var i = 0,
    duration = 0,
    root;

var all_path = [];
all_path[0] = "A.json";
all_path[1] = "B.json";

var path = [];
for (var i = 0; i < 2; i++)
        path[i] = all_path[i];
path[2] = path[0]; //Je copie le même path qu'un des deux path précédent, ce sera mon arbre total, ou je changerais simplement les données dedans.

create_a_tree_obj(path);

function multiple_click() {
    //onmousemove = function(e){console.log("mouse location:", e.clientX, e.clientY)}
    if (cursorX >= 0 && cursorX < 600) {
        simulateClick(cursorX + 600 - window.pageXOffset, cursorY - window.pageYOffset);
        simulateClick(cursorX + 1200 - window.pageXOffset, cursorY - window.pageYOffset);
    }
    else if (cursorX >= 600 && cursorX < 1200) {
        simulateClick(cursorX - 600 - window.pageXOffset, cursorY - window.pageYOffset);
        simulateClick(cursorX + 600 - window.pageXOffset, cursorY - window.pageYOffset);
    }
    else if (cursorX >= 1200) {
        simulateClick(cursorX - 600 - window.pageXOffset, cursorY - window.pageYOffset);
        simulateClick(cursorX - 1200 - window.pageXOffset, cursorY - window.pageYOffset);
    }
    else
        console.log("no , cursorX = " + cursorX + " , cursorY = " + cursorY);
}

function retrieve_content_svgs(all_g, i) {
    var all_aftertext = all_g.selectAll(".node tspan.aftertext"); //On récupère tout les aftertext, rect qui contient des nombres.
    var nodelist_tmp = Object.values(all_aftertext)[0][0]; //Conversion d'object à nodelist
    nb_data[i] = Array.prototype.slice.call(nodelist_tmp); //Conversion Nodelist a array
}

function add_up_svgs() {
    var tmp;
    setTimeout(function() {
        for (var i = 0; nb_data[2][i]; i++) {
            if (document.getElementById("abs").checked) {
                tmp = Number(nb_data[0][i].innerHTML) - Number(nb_data[1][i].innerHTML);
                if (tmp >= 0)
                    nb_data[2][i].innerHTML = "+" + tmp.toFixed(1);
                else
                    nb_data[2][i].innerHTML = "" + tmp.toFixed(1);
            }
            else if (document.getElementById("rel").checked) {
                tmp = (Number(nb_data[0][i].innerHTML) - Number(nb_data[1][i].innerHTML)) / Number(nb_data[0][i].innerHTML) * 100;
                if (tmp >= 0)
                    nb_data[2][i].innerHTML = "+" + tmp.toFixed(1) + " %";
                else
                    nb_data[2][i].innerHTML = "" + tmp.toFixed(1) + " %";

            }
            else {
                tmp = Number(nb_data[0][i].innerHTML) - Number(nb_data[1][i].innerHTML);
                if (tmp >= 0)
                    nb_data[2][i].innerHTML = "+" + tmp.toFixed(1);
                else
                    nb_data[2][i].innerHTML = "" + tmp.toFixed(1);
            }
            nb_data[2][i].setAttribute("x", (288 - nb_data[2][i].innerHTML.length * 6) - 7);
        }
    }, 1);
}

function create_a_tree_obj(path) {
    var i = 0;
    var div;
    var cell;

    if (i === 0) {
        div = d3.select("body").append("div")
            .attr("id", "div");
    }
    for (i ; path[i]; i++) {
        var nb_ent = i + 1;
        cell = div.append("div").attr("class", "cell").attr("id", "cell" + i);
        cell.append("p").text("Entreprise " + nb_ent + " - " + path[i]).attr("style", "font-family: Century Gothic,AppleGothic,sans-serif; font-size: 20px").attr("id", "title");
        svg_array[i] = cell.append("svg")
        .attr("id", "d" + 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);
    }
    cell.attr("class", "total").attr("id", "total");
    cell.select("#title").text("Comparatif");
    add_up_svgs();
    if (ent === 0) {
            create_ent_form(all_path);    
            ent++;
    }
}

function create_ent_form(all_path) {
    var ent1 = document.getElementById("ent1");
    var ent2 = document.getElementById("ent2");
    for (var i = 0; all_path[i]; i++) {
        var opt = document.createElement("option");
        opt.innerHTML = all_path[i];
        ent1.append(opt);
    }
    for (var i = 0; all_path[i]; i++) {
        var opt = document.createElement("option");
        opt.innerHTML = all_path[i];
        ent2.append(opt);
    }
}    

function button_clicked() {
    var path_tmp = [];
    document.getElementById("button").addEventListener("click", function (e) {
        path_tmp[0] = document.getElementById("ent1").options[document.getElementById("ent1").selectedIndex].text;
        path_tmp[1] = document.getElementById("ent2").options[document.getElementById("ent2").selectedIndex].text;
        path_tmp[2] = path_tmp[0];
        remove_and_replace(path_tmp);
    });
}

function remove_and_replace(new_path) {
    var div = d3.select("#div");
    var moteur = document.getElementById("moteur");
    moteur.remove();
    div.remove();
    create_a_tree_obj(new_path);
    document.body.appendChild(moteur);
}

function add_the_tree_graph(svg_array, path, i) {
    var root = [];

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

function update(source, svg_var, svg_id, all_sources) {
  // Compute the flattened node list.
    var nodes = source.descendants();
    var height = Math.max(50, nodes.length * barHeight + margin.top + margin.bottom);
    var i = 0;

    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", function (d) {
          return 'node ' + (d.children ? '' : 'child'); 
      })
      .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) {
      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.
      click_mult = 1;
    });
    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).attr("id", "afterText").text(afterText);
            // position aftertext
            afterTextSpan.attr('x', (288 - afterText.length * 6) - 5);
        } 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();
    console.log(nb_data[2]);
    retrieve_content_svgs(svg_array[2], 2);
    add_up_svgs();

}

function simulateClick(x, y) {
    var s = d3.select(document.elementFromPoint(x, y));
    s.on("click")(s.datum());
}

//Click multiple
setInterval(function(e) {
    if (click_mult === 1) {
        //console.log(nb_data[0].length + " " + nb_data[2].length);
        multiple_click();
        click_mult = 0;
    }
}, 1);

setInterval(button_clicked(), 1);

function color(d) {
  return d._children ? "#3182bd" : d.children ? "#c6dbef" : "#fd8d3c";
}

A.json文件:

{"attributes": "DPGF", "children": [{"attributes": "LOT:  nom 13.CVC", "children": [{"attributes": "Tous_DPGF:  Profondeur 1", "children": [{"attributes": "Poste:  Rang Rang 1 | 19", "children": [{"attributes":"Prix unitaire | 0.0"}, {"attributes":"Unité | 19.0"}, {"attributes":"Quantité"}, {"attributes":"Prix total"}]}, {"attributes": "Poste:  Rang Rang 1 |     40", "children": [{"attributes":"Prix unitaire | 20.0"}, {"attributes":"Unité | 20.0"}, {"attributes":"Quantité"}, {"attributes":"Prix total"}]}, {"attributes": "Poste:  Rang Rang 1 |     44", "children": [{"attributes":"Prix unitaire | 21.0"}, {"attributes":"Unité | 23.0"}, {"attributes":"Quantité"}, {"attributes":"Prix total"}]}, {"attributes": "Poste:  Rang Rang 1 |     49", "children": [{"attributes":"Prix unitaire | 24.0"}, {"attributes":"Unité |25.0"}, {"attributes":"Quantité"}, {"attributes":"Prix total"}]}, {"attributes": "Poste:  Rang Rang 1 |     53", "children": [{"attributes":"Prix unitaire |26.0"}, {"attributes":"Unité |27.0"}, {"attributes":"Quantité"}, {"attributes":"Prix total"}]}, {"attributes": "Poste:  Rang Rang 1 |     93", "children": [{"attributes":"Prix unitaire | 28.0"}, {"attributes":"Unité | 65.0"}, {"attributes":"Quantité"}, {"attributes":"Prix total"}, {"attributes": "Tous_DPGF:  Profondeur 2", "children": [{"attributes": "Prix total", "children": [{"attributes":"Prix unitaire | 31.0"}, {"attributes":"Unité | 65.0"}, {"attributes":"Quantité"}, {"attributes":"Prix total"}, {"attributes": "Tous_DPGF:  Profondeur 3", "children": [{"attributes": "Poste:  Rang Rang 4", "children": [{"attributes":"Prix unitaire | 35.0"}, {"attributes":"Unité| 35.0"}, {"attributes":"Quantité"}, {"attributes":"Prix total"}]}, {"attributes": "Poste:  Rang Rang 4", "children": [{"attributes":"Prix unitaire |36.0"}, {"attributes":"Unité |36.0"}, {"attributes":"Quantité"}, {"attributes":"Prix total"}]}, {"attributes": "Poste:  Rang Rang 4", "children": [{"attributes":"Prix unitaire| 37.0"}, {"attributes":"Unité |37.0"}, {"attributes":"Quantité"}, {"attributes":"Prix total"}]}, {"attributes": "Poste:  Rang Rang 4", "children": [{"attributes":"Prix unitaire    | 38.0"}, {"attributes":"Unité| 38.0"}, {"attributes":"Quantité"}, {"attributes":"Prix total"}]}, {"attributes": "Poste:  Rang Rang 4", "children": [{"attributes":"Prix unitaire  |39.0"}, {"attributes":"Unité   |39.0"}, {"attributes":"Quantité"}, {"attributes":"Prix total"}]}, {"attributes": "Poste:  Rang Rang 4", "children": [{"attributes":"Prix unitaire | 40.0"}, {"attributes":"Unité |41.0"}, {"attributes":"Quantité"}, {"attributes":"Prix total"}]}, {"attributes": "Poste:  Rang Rang 4", "children": [{"attributes":"Prix unitaire             | 42.0"}]}]}]}]}]}]}]}]}

B.json文件:

{"attributes": "DPGF", "children": [{"attributes": "LOT:  nom 13.CVC", "children": [{"attributes": "Tous_DPGF:  Profondeur 1", "children": [{"attributes": "Poste:  Rang Rang 1 |  32", "children": [{"attributes":"Debut_poste_Excel | 13.0"}, {"attributes":"Fin_poste_Excel | 19.0"}, {"attributes":"Mot_cle debut"}, {"attributes":"Rang Rang 1"}]}, {"attributes": "Poste:  Rang Rang 1 |  49", "children": [{"attributes":"Debut_poste_Excel | 29.0"}, {"attributes":"Fin_poste_Excel | 20.0"}, {"attributes":"Mot_cle chauffage"}, {"attributes":"Rang Rang 1"}]}, {"attributes": "Poste:  Rang Rang 1 |  52", "children": [{"attributes":"Debut_poste_Excel | 28.0"}, {"attributes":"Fin_poste_Excel | 23.0"}, {"attributes":"Mot_cle Préambule"}, {"attributes":"Rang Rang 1"}]}, {"attributes": "Poste:  Rang Rang 1 |  45", "children": [{"attributes":"Debut_poste_Excel | 19.0"}, {"attributes":"Fin_poste_Excel |25.0"}, {"attributes":"Mot_cle Préambule"}, {"attributes":"Rang Rang 1"}]}, {"attributes": "Poste:  Rang Rang 1 |  50", "children": [{"attributes":"Debut_poste_Excel |22.0"}, {"attributes":"Fin_poste_Excel |27.0"}, {"attributes":"Mot_cle production thermique"}, {"attributes":"Rang Rang 1"}]}, {"attributes": "Poste:  Rang Rang 1 |  99", "children": [{"attributes":"Debut_poste_Excel | 34.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"}]}]}]}]}]}]}]}]}

感谢您的帮助;)

0 个答案:

没有答案