2016-09-27 73 views
1

我使用D3创建条形图,并使用jquery来选择条形图。我遇到了一个问题,我不明白我在哪里使用$(this)选择了一个条形(矩形),而console.log()语句似乎证实了这一点。但是,我有问题获得某些功能(例如转换,样式)才能正常工作 - 错误消息表示它们不是函数。

我已经构建了我在下面遇到的问题的一个小例子。而不是条形图,只有两个矩形。我成功改变了宽度,但不能使用转换来平滑此更改,也无法使用$(this).style更改填充颜色。

感谢您的帮助!这是我的代码。

P.S.这是我的第一个StackOverflow问题,所以请让我知道如果我应该以不同的方式提出这个问题和/或是否有一些我没有遵循的约定。我在这个问题上花费了几天的时间进行了相当详尽的搜索,并且真的遇到了困难。再次感谢!

<body> 
    <svg width="1000" height="1000" id="this_svg"> 
     <rect x="0" y="0" width="100" height="100" fill="blue" data-color="red"> </rect> 
     <rect x="0" y="100" width="100" height="100" fill="green" data-color="purple"></rect> 
    </svg> 

    <script> 
     $ (document).ready(function() { 
      $svg = $("#this_svg") 
      rcts = $svg.find("rect") 
      // This Works Fine 
      rcts.each(function() { 
       $(this).attr("width", "500") 
      }); 
      // This breaks (see error message): 
      // Uncaught TypeError: $(...).transition is not a function 
      rcts.each(function() { 
       $(this).transition().duration(500).attr("width", "500") 
      }); 
      //... and if this hadn't already broken, this next part would 
      // break instead (see error message): 
      // Uncaught TypError: $(...).style is not a function 
      rcts.each(
       $(this).style("fill", function() { 
        return $(this).attr("data-color") 
      })); 
     }); 
    </script> 
</body> 
+2

问:为什么你有'd3js'因为如果你的代码不使用D3标签?顺便说一句,你得到这个错误,因为'transition()'是一个D3函数,而不是一个jQuery之一。 –

回答

1

d3 !== jquery,你不能叫上jquery选择的d3选择方法。 注意,方法名称有一些重叠(例如它们都有一个attr方法),但它们仍然不相同。

的简单的解决你的烦恼是使用d3过渡做:

d3.select(this).transition().duration(500).attr("width", "500"); 

这听起来像你需要阅读高达更好地了解的用例这两个库。在我看来,当编码为d3时,甚至不加载jquery。你不需要那个拐杖,而是用d3的方式来代替,从长远来看,你不会感到困惑。

+0

谢谢!快速提问:我的印象是,jquery允许你通过更好的选择器实现更高效的代码。我主要是使用jQuery作为编写较短代码的方式,与D3相比,DOM代码遍历DOM的时间更少。你只是说使用D3代码可以达到同样的效率? –

+0

@ RyanBaxter-King,为了回答你的具体问题,d3和jquery都在内部使用了相同的内置选择器方法,那里可能几乎没有性能差异。 **但是**你问的是错误的问题。你应该专注于编写干净的代码,这些代码很容易阅读,理解和重构。如果你想建立一个基于d3的可视化,你需要d3。恕我直言,在顶部混合jquery只会导致维护性较差的代码。 – Mark

1

如果您使用D3创建了条形图,则应使用相同的D3选择其元素。用jQuery选择这些元素是没有意义的。

您的代码将不起作用,因为transition()style都不是jQuery函数。话虽这么说,你应该使用D3来操纵你的元素:

var rects = d3.selectAll("rect"); 
 
rects.transition().duration(1000).attr("width", 500).attr("fill", function(){ 
 
return d3.select(this).attr("data-color"); 
 
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> 
 
<svg width="1000" height="1000" id="this_svg"> 
 
     <rect x="0" y="0" width="100" height="100" fill="blue" data-color="red"> </rect> 
 
     <rect x="0" y="100" width="100" height="100" fill="green" data-color="purple"></rect> 
 
    </svg>