JQuery/Javascript/d3 'on click' functionality not working as expected

时间:2016-02-12 20:49:45

标签: javascript jquery html d3.js svg

So, basically I've got 2 circles: circle1 and circle2 that have been drawn using d3. By default, circle1 appears and when it is clicked, it shows the div: 'Circle1 has been clicked'. On clicking the next button, circle2 appears and I want it to display the div: 'Circle2 has been clicked' when I click on circle2(this is the part that doesn't work).

out1 <- tapply(df$Price, df$Item, rosnerTest)

Javascript code:

<div class="questions">
    <div id="canvas1" class="v1"style="width:200px; height:135px;">Circle1</div>
    <div id="div1" class="clickable" style="display:none;">You clicked Circle1</div>
</div>

<div class="questions">
    <div id="canvas2" class="v1"style="width:200px; height:135px;">Circle2</div>
    <div id="div2" class="clickable" style="display:none;">You clicked circle2</div>
</div>

<input type="button" id="next" value="Next" onclick="sum_value()">

working fiddle so far: https://jsfiddle.net/La6w0pxy/

I know it can be done by attaching the circle(d3 object)to the divs separately(and hence svg's) and calling two separate functions. What I want to know is that, can it not be done by using an if statement as commented out below?

Thank you in advance!

1 个答案:

答案 0 :(得分:0)

所以,我想我正在考虑错误的思路。以下两种方法对我有用: 首先(通过分配id):

var whole = d3.select("#canvas1");
var wholeCanvas = whole.append("svg").attr("width", 200).attr("height", 135);
wholeCanvas.append("circle").attr("cx", 50)
                            .attr("cy", 50)
                            .attr("r", 40)
                            .attr("id", 'hey');

var whole2 = d3.select("#canvas2");
var whole2Canvas = whole2.append("svg").attr("width", 200).attr("height", 135);
whole2Canvas.append("circle").attr("cx", 50)
                            .attr("cy", 50)
                            .attr("r", 40)
                            .attr("id", 'hey2');

$("#hey").on("click", function(){
    $("#div1").show();
});

$("#hey2").on("click", function(){
    $("#div2").show();
});

更新了它的小提琴:https://jsfiddle.net/La6w0pxy/4/

第二个(没有指定id):

var whole = d3.select("#canvas1");
var wholeCanvas = whole.append("svg").attr("width", 200).attr("height", 135);
wholeCanvas.append("circle").attr("cx", 50)
                            .attr("cy", 50)
                            .attr("r", 40)
                            .on("click", function(d){
                            $("#div1").show();
                            });

var whole2 = d3.select("#canvas2");
var whole2Canvas = whole2.append("svg").attr("width", 200).attr("height", 135);
whole2Canvas.append("circle").attr("cx", 50)
                            .attr("cy", 50)
                            .attr("r", 40)
                            .on("click", function(d){
                            $("#div2").show();
                            });

更新了小提琴:https://jsfiddle.net/La6w0pxy/5/