删除d3.js中的元素

vko*_*syj 2 javascript d3.js

NewBie for d3.js. 我尝试根据方法删除xAxis

.s.selectAll( "G")除去(x-轴);

但它不起作用.不确定是否是删除xAxis的正确方法?先感谢您.

1. var xAxis = d3.axisBottom()
    .scale(xScale);


2. s.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis)

3. s.selectAll("g").remove(xAxis);
Run Code Online (Sandbox Code Playgroud)

And*_*eid 6

.remove() 不带任何参数,它只是一种可以用于任何d3选择的方法.

要删除功能,您必须先选择它们,然后将其删除:

d3.selectAll('g').remove(); // removes all 'g' elements from the DOM.
d3.selectAll('.point').remove(); // removes all elements with the class 'point'
Run Code Online (Sandbox Code Playgroud)

为了说明,以下代码绘制了一个圆圈:

var svg = d3.select('body').append('svg');

var circle = svg.append('circle')
  .attr('cx',40)
  .attr('cy',40)
  .attr('r',10);
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
Run Code Online (Sandbox Code Playgroud)

您可以通过多种方式删除圈子.您可以使用circle.remove();变量作为circle包含该圆的选择.

或者您可以选择svg中的圆圈: svg.selectAll('circle').remove();

或者您可以选择circleDOM中的所有sd3.selectAll('circle').remove();

方法1:

var svg = d3.select('body').append('svg');

var circle = svg.append('circle')
  .attr('cx',40)
  .attr('cy',40)
  .attr('r',10);
  
circle.remove();
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
Run Code Online (Sandbox Code Playgroud)

方法2:

var svg = d3.select('body').append('svg');

var circle = svg.append('circle')
  .attr('cx',40)
  .attr('cy',40)
  .attr('r',10);
  
svg.selectAll('circle').remove();
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
Run Code Online (Sandbox Code Playgroud)

方法3:

var svg = d3.select('body').append('svg');

var circle = svg.append('circle')
  .attr('cx',40)
  .attr('cy',40)
  .attr('r',10);
  
d3.selectAll('circle').remove();
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
Run Code Online (Sandbox Code Playgroud)

在您的情况下,您可以尝试上述方法的变体:

var axis = s.append("g")
            .attr("class", "x axis")
            .attr("transform", "translate(0," + height + ")")
            .call(xAxis);

axis.remove();
Run Code Online (Sandbox Code Playgroud)

或者你可以给它一个类或id并使用它来删除它:

s.append("g")
            .attr("class", "x axis")
            .attr('id', 'xAxis')
            .attr("transform", "translate(0," + height + ")")
            .call(xAxis);

d3.selectAll('#xAxis').remove();
Run Code Online (Sandbox Code Playgroud)