D3:在mouseover / mouseout上输入(),exit()

时间:2018-02-06 18:31:23

标签: javascript jquery html d3.js

我有一个函数,在线图上的点上鼠标悬停时,调用Twitter API并获取与其时间戳相关联的推文。然后添加嵌套的div和与数据对应的元素。我的问题是,在mouseout上,我想从DOM中删除该div及其相关数据,这样当我将鼠标悬停在另一个点上时,会创建一个包含相关数据的新面板。

我的鼠标悬停看起来像这样:

.on("mouseover", function(d,i){
    var tweetDivs = d3.select(".panel").selectAll("div.panel-body")
                      .data(tweet_list)
                      .enter()
                      .append("div")
                      .attr("id", function(d){return "p"+d['id_str']})
                      .classed("panel-body", true);

                tweetDivs.append("img")
                    .attr("width", 20)
                    .attr("height", 20)
                    .attr("src", function(d){return d['user']['profile_image_url']})
                    .classed("panel-tweet-img-profile", true);

                tweetDivs.append("p")
                    .text(function(d){
                        var tweet_created_format = d3.timeFormat("%-I:%M%p, %e %b %Y")(d3.timeParse("%a %b %d %H:%M:%S %Z %Y")(d['created_at']));
                        return "@"+d['user']['screen_name']+"    ("+tweet_created_format+")";
                    })
                    .classed("panel-tweet-text-header", true);

                tweetDivs.append("p")
                    .text(function(d){return d['text'];})
                    .classed("panel-tweet-text-body", true);

                var infoBlock = tweetDivs.append("p")
                                .classed("panel-tweet-info-block", true);

                infoBlock.append("img")
                    .attr("src", imgRetweet)
                    .classed("panel-tweet-img-retweet", true);
                infoBlock.append("text")
                    .text(function(d){
                        return d['retweet_count'];
                    })
                    .classed("panel-tweet-text-retweet", true);

                infoBlock.append("img")
                        .attr("src", imgFav)
                        .classed("panel-tweet-img-favorite", true);
                infoBlock.append("text")
                    .text(function(d){
                        return d['favorite_count'];
                    })
                .classed("panel-tweet-text-favorite", true);
});

我的mouseout函数用于删除它,具有以下exit()函数:

    .on("mouseout", function(d,i){
        // exit()
        var panelRemove = d3.select(".panel-body");

        panelRemove.data(tweet_list)
                    .exit()
                    .remove();
    });

我不确定它是什么我做错了因为我已经传递了相同的数据要在这里删除。我也试过d3.select(".panel").selectAll("div.panel-body")但没有任何反应。

初始面板显示绝对正常,包含所有相关数据。但是mouseout没有删除它,我无法显示新的面板。

1 个答案:

答案 0 :(得分:1)

由于您将相同的tweet_list数据传递给panelRemove选项,因此exit()代码无法找到要删除的节点。 exit().remove()将删除不再在数据中表示的现有节点。如果您要将空的推文列表作为新数据传入,exit().remove()应删除节点。

相关问题