[英]D3 force layout - legend interactivity on/off
我有一個帶有圖例的部隊布局,並且已將復選框附加到圖例中的每個角色。 我正在嘗試遵循此示例( https://jsfiddle.net/zhanghuancs/cuYu8/ ),並向圖例添加交互性,但是當我取消選中任何復選框時,所有鏈接都會消失,而不是與之相關的鏈接和節點角色。 我正在使用此循環創建圖例,
var col = color(d.group);
// adding code to display legend
// as nodes are filled
if(!(d.role in roles)){
legend.append("li")
.html(d.role)
.style("color", col)
//add checkbox
.append("input")
.attr("type", "checkbox")
.attr("id", function (d){
return "chk_" + d;
})
//check box
.property("checked", true)
.on("click", function (d){
//click event
var visibility = this.checked? "visible" : "hidden";
filterLegend(d,visibility);
})
roles[d.role] = true;
}
return col; })
這是我的圖表的小提琴( https://jsfiddle.net/gbhrea/077mb7o1/1/ ),它使用了大量數據,因此只使用了一個小樣本作為小提琴。 (圖形不會顯示在小提琴上,但是無論如何都會保持鏈接,以便可以看到完整的代碼)
這是更改可見性的代碼
function filterLegend(aType, aVisibility){
//change vis of link
link.style("visibility", function (o) {
var lOriginalVisibility = $(this).css("visibility");
return o.type === aType ? aVisibility : lOriginalVisibility;
});
//change vis of node
//if links of node invisible, node should be too
node.style("visibility", function (o, i) {
var lHideNode = true;
link.each(function (d, i) {
if (d.source === o || d.target === o) {
if ($(this).css("visibility") === "visible") {
lHideNode = false;
}
}
})
});
} //end filter
明確地說,我要實現的是-當我取消選中角色(例如Actor)時,所有節點和鏈接都消失了。 任何指針將不勝感激:)
您的代碼中有一些錯誤。 首先,您沒有將任何數據綁定到圖例元素,因此.on("click", function (d) { })
無效,因為未在其中定義d
。 不過,您的確有d.role
,因此應該將其傳遞給函數。
同樣,您的filterLegend()
函數引用未定義的事物( .type
)-這就是為什么現在所有內容都消失的原因。 您傳遞的是未定義的內容,並將其與未定義的內容進行比較,結果為true
。 此外,鏈接不直接具有節點信息,而是在.source
和.target
,因此您需要與.source.role
和.target.role
進行比較。
另一方面,對於節點而言,這比當前代碼要嘗試的要容易得多-無需遍歷鏈接。 除了與現有.role
屬性(而不是不存在的.type
進行比較之外,您可以在此處使用鏈接所具有的代碼。
在此處完成演示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.