javascript - 使用 selectAll() 到达特定类

标签 javascript html d3.js dom

我有一个选择 g 标签的变量(我们称她为 all_g)。我想选择这个 g 的一些内容。

所以这是我的 g 标签中的内容: The G-tag

我想覆盖所有其他 afterText 内容,例如这个包含“19”的内容。所以我试着去做:

var all_aftertext = all_g.selectAll(".node tspan.aftertext");

但它返回一个空的 NodeList。我怎样才能轻松选择它?

这是我的代码中的函数,我试图在其中检索所有后文:

function add_total_svg(all_g, cell) {
    var all_aftertext = all_g.selectAll(".node tspan.aftertext");
    //for (var i = 0; )
    console.log(all_aftertext);
    cell.attr("class", "total").attr("id", "total");
    cell.select("#title").text("Total");
}

这是我的全部代码:

<!DOCTYPE html>
<head>

    <meta charset="utf-8"> 
    <title>Graphique DPGF</title>
    <style>

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

</style>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>

//Initialisation des variables, marge, hauteur, incrementation 'i' etc ..
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 loop;
var cursorY;
//stack_nb variable
var nb_data = [
    [], [], []
];
var nb_tmp = 0;
var nb = 0;
var i = 0;
var do_it = 0;

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

var i = 0,
    duration = 0,
    root;


var path = [];
path[0] = "A.json";
path[1] = "A.json";
path[2] = "A.json";
var value = [];
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);
}

//Changez le last_svg
function add_total_svg(all_g, cell) {
    var all_aftertext = all_g.selectAll(".node tspan.aftertext");
    //for (var i = 0; )
    console.log(all_aftertext);
    cell.attr("class", "total").attr("id", "total");
    cell.select("#title").text("Total");
}  

function stack_nb(str_nb) {
    if (nb > nb_tmp) {
        nb_tmp = nb;
        i = 0;
    }
    nb_data[nb][i] = Number(str_nb);
    i++;
}


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");
        cell.append("p").text(path[i]).attr("style", "font-family: Helvetica").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);
    }
    add_total_svg(svg_array[i - 1], cell);
}

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(json);
            root[i].x0 = 0;
            root[i].y0 = 0;
            nb = i;
            do_it = 1;
            update(root[i], svg_array[i], "d" + i, root);
        }
    });
}    


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

    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.
      loop = 1;
      return;
    });
    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
        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();
}
function simulateClick(x, y) {
    var s = d3.select(document.elementFromPoint(x, y));
    s.on("click")(s.datum());
}

setInterval(function(e){
    if (loop === 1) {
        multiple_click();
        loop = 0;
    }
}, 1);

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

</script>
<br>

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"}]}]}]}]}]}]}]}]}

谢谢。

最佳答案

这里的问题很容易发现,但对于不了解异步代码的人来说理解起来却相当复杂。那么,让我们从一个笑话开始:

There are two types of programmers: and those who don't. Those who understand asynchronous code...

那么,这里的问题是什么?如果您查看 create_a_tree_obj 中的代码你会看到它按顺序调用:

  1. add_the_tree_graph
  2. add_total_svg

因此,由于add_the_tree_graphadd_total_svg 之前运行那些<tspans>应该在那里,对吧?

错了。里面add_the_tree_graph你有这个:

d3.json(path[i], function(error, json) {
    if (error) throw error;
    //etc...
});

这就是我们谈到的异步代码。 d3.json的回调不会立即运行,到 add_total_svg 时被调用,没有没有 <tspan>还没有。


虽然这个问题已经在 S.O. — this question作为最好的欺骗目标——我认为这里的代码应该得到一个具体的答案,因为异步代码的位置不太明显。

关于javascript - 使用 selectAll() 到达特定类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52420645/

相关文章:

javascript - Node (ES6) : SyntaxError: Unexpected token {

c# - 将 html 文本框值从用户控件传递到 aspx 页面

html - 向表格的所有侧面添加 CSS 阴影

javascript - 在 div 已经附加到一个 div 之后,将 div 附加到另一个 div

javascript - 正则表达式匹配变量

javascript - 有没有办法增加 Google Chrome 中 localStorage 的大小以避免 QUOTA_EXCEEDED ERR : DOM Exception 22

javascript - 将表数据添加到可编辑的 DataTables 中会删除过滤器

javascript - 使用 d3 排列刻度文本的最佳方式

javascript - D3 : `bubble.nodes` not applying correct graphical data to dataset

javascript - D3 : + operator before object call