2013-07-02 4 views
28

SVG 요소에 여러 클래스 이름을 사용하여 실험하고 있으므로 selectAll과 클래스 이름의 "parts"를 사용하여 SVG 요소의 하위 집합을 선택할 수 있습니다. 불행히도 나는 작품을 시도하지 않았고 온라인에서 예제를 찾지 못했습니다. 아래의 코드는 내가 네 개의 동그라미의 간단한 예제로 무엇을하려하는지 보여줍니다. 두 개의 원은 클래스 이름이 "mYc 101"이고 두 개의 원은 클래스 이름이 "mYc 202"입니다. selectAll (". mYc")은 네 개의 모든 원을 제공합니다. 수업 이름이 'mYc 101'인 서클 만 원한다면 어떻게해야합니까? 이 작업을 수행 할 수 있습니까? 방법? 감사 시간 무한대 !!D3 selectAll을 여러 클래스 이름으로 사용하는 방법

<!DOCTYPE html> 
<meta charset="utf-8"> 
<body> 
<div id="my_div"></div> 
<script src="http://d3js.org/d3.v3.min.js"></script> 
<script> 
    var m_div = d3.select("#my_div"); 
    var m_svg = m_div.append("svg"); 

    var g = m_svg.append("g"); 

    g.append("circle") 
     .attr("class", "mYc 101") 
     .attr("cx", 100) 
     .attr("cy", 100) 
     .attr("r", 50) 
     .attr("style", "stroke: green; stroke-width: 8; fill: #000000"); 

    g.append("circle") 
     .attr("class", "mYc 101") 
     .attr("cx", 300) 
     .attr("cy", 100) 
     .attr("r", 50) 
     .attr("style", "stroke: green; stroke-width: 8; fill: #000000"); 

    g.append("circle") 
     .attr("class", "mYc 202") 
     .attr("cx", 100) 
     .attr("cy", 300) 
     .attr("r", 50) 
     .attr("style", "stroke: blue; stroke-width: 8; fill: #000000"); 

    g.append("circle") 
     .attr("class", "mYc 202") 
     .attr("cx", 300) 
     .attr("cy", 300) 
     .attr("r", 50) 
     .attr("style", "stroke: blue; stroke-width: 8; fill: #000000"); 

    // This selects all four circles 
    var list = d3.selectAll(".mYc"); 

    // But if I want to select only class "mYc 101", none of these work. 
    // In fact they all give an error. 
    // var list1 = d3.selectAll(".mYc 101"); 
    // var list1 = d3.selectAll(".mYc .101"); 
    // var list1 = d3.selectAll(".mYc.101"); 
    // var list1 = d3.selectAll(".mYc,.101"); 
    // var list1 = d3.selectAll(".101"); 

</script> 
</body> 

답변

40

filter 방법을 사용하여 선택기 체인 될이 작업을 수행하는 가장 D3 방법 :

var list1 = d3.selectAll(".mYc").filter(".101"); 

클래스 이름은 숫자로 시작할 수 없기 때문에이 그래도 작동하지 않습니다. 그래서 당신은 "101"와 같은 뭔가 이름을 변경해야하고 당신은

var list1 = d3.selectAll(".mYc").filter(".a101"); 

this fiddle를 참조 할 수 있습니다.

+0

정말 고맙습니다. 핵심은 클래스 이름이 숫자로 시작할 수 없다는 사실이었습니다. Bill –

31

내가이 일을 발견 한 또 다른 방법은 예를 들어, 하나의 문자열로 동시에 두 클래스를 선택하는 것입니다

var list1 = d3.selectAll(".mYc.a101") 

당신이 사이에 공간을 추가 할 경우 작동하지 않습니다, 또는 사이에 쉼표를 추가하십시오 (두 클래스 중 하나를 선택하는 경우).

+0

Lars의 답변은 더 풍부하지만, 이것이 나를 이해하는 데 도움이되었습니다. –

+0

또한,'var list1 = d3.selectAll ("circle.mYc.a101")' – Felix

관련 문제