簡體   English   中英

如何獲取d3.select的父節點

[英]How to get the parent node of d3.select

同樣,我不知道如何獲得所需的信息。

對於以下 SVG 對象,我需要獲取組標簽:

<g id="a39" style="touch-action: none; -webkit-tap-highlight-color: rgba(0, 0, 0, 0);" transform="translate(0 0)">
  <line class="hotwater graphic selectedGraphic" x1="400" y1="-70" x2="670" y2="-70" id="g39"></line>
  <line class="hotwater graphic selectedGraphic" x1="400" y1="-50" x2="670" y2="-50" id="g39"></line>
</g>

<g id="a40" style="touch-action: none; -webkit-tap-highlight-color: rgba(0, 0, 0, 0);">
  <polyline class="warmbrinewater graphic selectedGraphic" fill="none" points="300,-20,240,-160,50,-90,300,-20" id="g40"></polyline>
</g>

我的選擇器是類selectedGraphic 我需要為封裝組標簽分配翻譯。 但我不知道如何獲得父節點......

d3.selectAll('.selectedGraphic').**FIRSTELEMENTSPARENT**.attr("transform", "translate(" + xPos + " " + yPos + ")");

有任何想法嗎?

謝謝,卡斯滕

更新:

其實我是這樣解決的:

var sel = document.getElementsByClassName('selectedGraphic');
for (var i = 0; i < sel.length; i++) {
    sel[i].parentNode.setAttribute('transform', "translate(" + xPos + " " + yPos + ")");
}

但我很樂意使用 d3 解決它。

您可以使用node().parentNode選擇父級,如下所示:

d3.selectAll('.selectedGraphic').node().parentNode;

這將返回父節點,但不確定是否必須對其執行另一個d3.select()

所以,如前所述,我將自己回答我的問題。

因為我的問題沒有解決方案,所以我解決了另一個問題。 我需要訪問封裝 g-tag,因為我想通過為組分配變換來移動所有 svg 對象。 我的選擇基於我分配給線條的“selectedGraphic”類(在這種情況下),帶有點擊事件。

現在,當單擊元素(它們捕獲事件)時,我只是在 g-tag 中添加了一個“可移動”類。 現在選擇這個類進行移動。

為了將來的需要,我添加了一個簡單的遞歸函數,它獲取每個孩子的第一個父母,在一個 svg 區域內:

function getFirstParent(svgChild) {
  //svgChild ist ein DOM-Object, kein d3-Object
  if (svgChild.parentNode.tagName == 'svg')
    return svgChild;
  else
    return getFirstParent(svgChild.parentNode);
}

結果是一個簡單的 DOM-Object,所以我仍然沒有使用 d3 解決這個問題的有效解決方案。

也許這對其他人有幫助:)

如果您仍然對 d3 解決方案感興趣,可以這樣做:

d3.selectAll(".selectedGraphic").each(function () {
  d3.select(this.parentElement).attr("transform", `translate(${xPos},${yPos})`);
});

在 TypeScript 中相同:

d3.selectAll<Element, null>(".selectedGraphic").each(function () {
  d3.select(this.parentElement).attr("transform", `translate(${xPos},${yPos})`);
});

暫無
暫無

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

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