簡體   English   中英

querySelectorAll是在多個圖表中選擇元素的好方法嗎?

[英]Is querySelectorAll a good way to select elements in multiple charts?

我想在多個圖表中突出顯示來自同一維度(此示例中為國家/地區)的元素。 在生成rectcircle為每個國家/地區分配一個類,然后使用querySeletorAll查找所有匹配的元素似乎可行,但是我想知道是否有更好的方法。 感覺有點。

請查看此以獲取有效的演示。

條形圖和散點圖都具有以相同方式分配給它們的元素( rectcircle )的類:

var enter = svgContainer.selectAll('rect')
  .data(data)
  .enter().append('rect')
  .attr('class', function(d) { return "mycharts_bars_" + d.Country; })

然后懸停時的突出顯示是:

  .on("mouseover", function(d) { 

  var hover_value = this.__data__.Country; 
  var hover_elems = document.querySelectorAll(`[class*="${hover_value}"]`);

  for (let item of hover_elems) {
    item.setAttribute('fill', 'hotpink');}
    })

如您在源代碼中所看到的, d3.selectAll已在內部使用document.querySelectorAll

export default function(selector) {
  return typeof selector === "string"
      ? new Selection([document.querySelectorAll(selector)], [document.documentElement])
      : new Selection([selector == null ? [] : selector], root);
}

因此,您可以安全地使用selectAll ,這對於D3程序員來說使您的代碼更加慣用。

但是,您的代碼中存在一些問題:

首先,您不需要var hover_value = this.__data__.Country; 您已經將基准作為第一個參數! 因此,它可以只是d.Country

其次,如果不需要,則不需要處理類,只需選擇元素。 您可以根據需要使用類,這不是什么大問題,但是for...of循環,您絕對不需要。 根據經驗,請勿在D3代碼中使用循環(在某些特定情況下需要使用循環,但不需要這種情況)。

綜上所述,該函數可以簡單地是這樣的:

d3.selectAll("circle, rect").attr("fill", function(e) {
    return e.Country === d.Country ? "pink" : "grey"
});

或者,因為僅將鼠標懸停在矩形上會更改顏色:

d3.select(this).attr("fill", "pink");
d3.selectAll("circle").attr("fill", function(e) {
    return e.Country === d.Country ? "pink" : "grey"
});

附帶說明,這將更改頁面中所有選定的元素。 我這樣做只是因為在您的示例中,您只有很少的元素。 如果您的真實圖表中有數百個元素,那么更好的解決方案是先過濾它們,然后再應用更改( mouseovermouseout ),這樣可以提供更好的性能。

這是您所做的更改的代碼: https : //blockbuilder.org/GerardoFurtado/e54f2f0cc711b51be4b400627cac6f51

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM