简体   繁体   English

如何将D3与JavaScript事件一起使用

[英]How do I use D3 with JavaScript events

Am trying to draw d3 charts when a button is clicked. 我试图在单击按钮时绘制d3图表。 But all the d3 tutorials I've seen says the d3 code should be placed inside the element you want the charts to appear. 但是我见过的所有d3教程都说d3代码应该放在希望图表出现的元素内。 This means the d3 code will execute when the page loads but I want the code to run only when a button is clicked. 这意味着d3代码将在页面加载时执行,但我希望代码仅在单击按钮时才能运行。

I also want to know if I can place my d3 code in an external file wrapped in a function that I can call when I want to. 我还想知道是否可以将d3代码放在包装在函数中的外部文件中,该函数可以在需要时调用。 If no, how do i create button that will show a d3 chart when clicked? 如果不是,我如何创建单击时将显示d3图表的按钮?

HTML 的HTML

<input type="button" Value="show" />

<div id="presentation">
<!-- bar charts to show up here when the "show" button is clicked.
     The button makes an ajax call and gets a json that contains data
     that will be used to draw the chart.
 -->
</div>

Check this out: http://jsfiddle.net/rUtS5/ 检查一下: http : //jsfiddle.net/rUtS5/

Edit CSS first 首先编辑CSS

#presentation {
   ...
   display: none;
}

Then add a blank class on your buttons 然后在按钮上添加一个空白类

<input type="button" Value="show" class="example" />

Use jQuery 使用jQuery

<script>
     $(".example").click(function () {
         $('#presentation').fadeIn("slow");
     });
</script>  

Result: 结果:

presentation div will not be seen when the page load. 页面加载时将看不到presentation div。 When someone click the button which has example class it will be seen. 当有人单击具有示例类的按钮时,将看到它。

You can also use toggle() , slideToggle() or fadeToggle() functions instead fadeIn() for show/hide property. 您还可以使用toggle()slideToggle()fadeToggle()函数来代替showIn / Hide属性的fadeIn()

I hope it helps... :/ 希望对您有所帮助...:/


PS If you try this solution PS如果您尝试此解决方案

add this code in <head> section <head>部分添加此代码

<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>

and use jQuery codes at the bottom of page before </body> 并在</body>之前的页面底部使用jQuery代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM