在d3图中单击时更改节点颜色

时间:2012-03-24 14:52:17

标签: jquery d3.js

我想在点击节点时更改节点的颜色。我有一些jquery来点击<div>来获取和显示一些用户信息:

 node.on("click", function(d) { 

    $.get("/user_info/" + d.name, function(data){

            $("#user").html(data);

        });

如果可能,我希望能够选择相同代码中的节点并更改其颜色。

由于

1 个答案:

答案 0 :(得分:0)

你好吗?

我不确定您是否要在单击节点或请求结束后执行此操作,因此请使用以下代码并使用您需要的内容。

注意我正在使用.call方法,它允许您更改函数的范围(并将参数传递给它)。

用法基本上是

(function(){ console.log(this); console.log(arguments); }).call({ obj: "Hi, i'm the scope"},1,2,3,4,5,6);

在firebug中运行它以查看它的作用!

因此,该函数看起来像:

node.on("click", function(d) {
    //In this context, 'this' is the element that got clicked
    $(this).css({ background: 'red' }); //Changes to red when clicked

    $.get("/user_info/" + d.name, (function(data){
            $(this).css({ background: 'blue' }); //Changes to blue when finished
            $("#user").html(data);

    }).call(this)); //'this' in this context refers to the node that was clicked, so we pass it as a scope for the anonymous function that will handle your request
});

干杯!

相关问题