使用单选按钮显示/隐藏内容 [英] Using Radio Buttons to Show/Hide Content
问题描述
我有JSON形式的数据,并且正在尝试使用D3.js将其可视化。我想让用户可以选择他们查看数据的图表。我试图没有成功地在两者之间进行平滑过渡,所以我决定只用单选按钮来完成。这是我得到的:
$(document).ready(function(){
if($(输入[name ='chart']:checked)。val()=='pie'){
// ... Graph 1
} else if($(input [name ='图表'):选中)。val()=='bar'){
// ...图表2
}
});
这显示了加载单选按钮时关闭的图形。但是,当我点击按钮时,它们不会改变。我做了一些研究,发现我可能需要包含change()函数。这是我试过的:
$(document).ready(function(){
$(input [ ($(#chart1Pie)。attr(checked)){
// ...图表1
} else if($(#chart1Bar)。attr(checked)){
// ...图2
}
});
} );
这有一些问题。 1)加载页面时,所选图形不加载。 2)单击单选按钮时,仅显示饼图。 3)单击另一个单选按钮时,上一个图形不会消失;它只是把新的一个放在它下面。
我看了几个StackOverflow的问题,他们都没有解决这个问题。有人可以帮我吗?感谢!
您需要做3件事才能实现。
$ b
$('#p $) 。图表')空();
2:而非:
if($(#chart1Pie)。attr(checked))
$ b $ <$>
$ $ $ $ $ $ $#chart1Pie :checked)))
3:在声明<$ c
$ $ $''$ c $。$''input:radio:第一 ')触发(' 变更');
它会触发它并显示一个图形。
小提琴: http://jsfiddle.net/k3WJN/13/
I have data in the form of JSON, and I'm trying to visualize it using D3.js. I want to give the user the option of what graph they view the data in. I tried, without success, to do a smooth transition between the two, so I decided to just do it with radio buttons. Here is what I got:
$(document).ready(function () {
if ($("input[name='chart']:checked").val() == 'pie') {
// ... Graph 1
} else if ($("input[name='chart']:checked").val() == 'bar') {
// ... Graph 2
}
});
This shows the graph that has its radio button checked off when it loads. However, when I click the buttons, they don't change. I did some research and found that I likely need to include the change() function. Here is what I tried:
$(document).ready(function () {
$("input[name=chart]:radio").change(function () {
if ($("#chart1Pie").attr("checked")) {
// ... Graph 1
} else if ($("#chart1Bar").attr("checked")) {
// ... Graph 2
}
});
});
There are a few things wrong with this. 1) The selected graph does not load when the page is loaded. 2) When a radio button is clicked, only the pie chart appears. 3) When the other radio button is clicked, the previous graph does not go away; it just puts the new one below it.
I've looked at several StackOverflow questions, and none of them solved the problem. Can someone help me out? Thanks!
You have 3 things to do to make it work.
1: Before entering into the first condition, do this :
$('#chart').empty();
2: instead of :
if ($("#chart1Pie").attr("checked"))
do :
if ($("#chart1Pie").is(":checked"))
3: Right after declaring the .change()
function, insert this :
$('input:radio:first').trigger('change');
it will trigger it and show a graph.
Fiddle : http://jsfiddle.net/k3WJN/13/
这篇关于使用单选按钮显示/隐藏内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!