javascript - 一般更新模式,在新文件上传时旧的不会删除

标签 javascript d3.js fileapi

我是 d3 的新手,所以我对一般更新模式有疑问(我研究了我在网上能找到的所有内容)。

所以,我正在创建 Web 应用程序,我使用 FileAPI (getAsUrl) 从 PC 上传 .csv 数据,这部分工作正常,但是当我在第一个文件之后上传任何内容时,所有数据都显示在图表上,来自所有上传的 .csv -s。 目前唯一的解决办法是在新的上传刷新浏览器之前,但这对用户不友好!

任何帮助将不胜感激:)

P.S: 如果我使用 Windows,IDE 是 VScode,图表是带回归线的散点图。

// setting graph, it's not all code for graph
const svg = d3.select(".chart")
   .append("svg")
const x = d3.scaleLinear()
const y = d3.scaleLinear()


//uploading file

//reading in data to chart
function drawChart(url) {         

  //Read the data
   {

    d3.entries(dataset); // pretvara 'object' u 'array'

// Add dots
  var renderChart = (selection, {dataset}) => {
    let dots = selection.selectAll(".dot")
    .data(dataset);
    dots.join (
      enter =>
        enter
              .append("circle")
              .attr("cx", (d) => x(d.x))
              .attr("cy", (d) => y(d.y))
              .attr("r", 4)
              .attr("fill", "#69b3a2")
              .attr("opacity", 0.7)
    ),
      update =>
        update
          .attr("cx", (d) => x(d.x))
          .attr("cy", (d) => y(d.y))
          .attr("r", 4)
          .attr("fill", "#69b3a2")
          .attr("opacity", 0.7),
        dots
          .exit().remove();

    }
});
}  // that's just scatter plot, there is more code for regression

document.getElementById('file_input').addEventListener('change', getAsUrl, false); 



//in HTML file this is input for button
<input type="file" id="file_input" name="files[]" accept=".csv"  multiple />

正如我所写,在第一次 .csv 上传时一切正常,但在每次下一次上传时,旧点保留而新点被添加。

最佳答案

您的join 结构不正确。根据documentation ,这应该是这样的:

selection.join(enter[, update][, exit])

如您所见,exit 选择是第三个参数(括号说明第二个和第三个参数都是可选的)。更明确地说,仍然根据相同的文档:

.join(
    enter => enter.append("circle"),
    update => update,
    exit => exit.remove()//3rd argument
  )

除此之外,您的更新 部分也不正确,您可以看到它位于join 方法之外。

话虽这么说,你的功能应该是:

dots.join(
  enter => enter.append("circle")
  .attr("cx", (d) => x(d.x))
  .attr("cy", (d) => y(d.y))
  .attr("r", 4)
  .attr("fill", "#69b3a2")
  .attr("opacity", 0.7),
  update => update.attr("cx", (d) => x(d.x))
  .attr("cy", (d) => y(d.y))
  .attr("r", 4)
  .attr("fill", "#69b3a2")
  .attr("opacity", 0.7),
  exit => exit.exit().remove()
);

关于javascript - 一般更新模式,在新文件上传时旧的不会删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57984266/

相关文章:

d3.js - 配置 d3 以使用 angular2 和 typescript 的正确方法

html - Google Chrome Base64 方法是否能够处理来自文件 API 的二进制数据?

html - 在 jsFiddle 中工作的 FileReader API,但不是来自本地文件

javascript - 使用 yyyy-mm-dd 格式查找数组中的最小和最大日期

javascript - 如何使用全局延迟js文件和单独的独立javascript文件

javascript - D3,将工具提示添加到水平条形图,工具提示不显示

javascript - 使用 D3 JavaScript 进行 X 轴缩放

javascript - 如何将硬编码文件路径传递给 File API?

javascript - 如何在文件中写入文本/模板并将其包含到项目中

javascript - 更改域名;操作点击的链接