如何调用“点击”在 d3 中以编程方式事件?

发布于 2024-12-29 22:43:49 字数 1861 浏览 0 评论 0原文

我正在尝试这样做(也在https://gist.github.com/1703994):

<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script type="text/javascript" src="http://mbostock.github.com/d3/d3.js?1.27.2"></script>
    <script type="text/javascript" src="http://mbostock.github.com/d3/d3.time.js?1.27.2"></script>

    <script type="text/javascript" src="js-libs/jquery-1.7.js"></script>

    <style>
      <!--
      #test {
      width: 400px;
      height: 500px;
      }
      -->
    </style>
  </head>

  <body>

    <script type="text/javascript">
      $(function() {
        var w = 600,
            h = 350;

        var vis = d3.select("#test").append("svg:svg")
        .attr("width", w)
        .attr("height", h)
        .append("svg:g")
        .attr("transform", "translate(" + w / 2 + "," + h / 2 + ")");

        var g = vis.selectAll("g")
        .data([ { x:1 , y: 2} ])
        .enter().append("svg:g");

        g.append("svg:path")
        .attr("fill", "red")
        .attr("stroke", "red")
        .attr("stroke-width", "10")
        .attr("d", "M 100 350 l 150 -300")

        g.select("path")
        .on("click", function() { console.log("Hello"); });

        // XXX: how to execute click programmaticaly?
      })
    </script>

    <div id="test"></div>
  </body>
</html>

但不起作用

我认为我们可以使用 https://github.com/mbostock /d3/wiki/Internals#wiki-dispatch_on

但是该怎么做呢?

I'm trying like that (also at https://gist.github.com/1703994):

<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script type="text/javascript" src="http://mbostock.github.com/d3/d3.js?1.27.2"></script>
    <script type="text/javascript" src="http://mbostock.github.com/d3/d3.time.js?1.27.2"></script>

    <script type="text/javascript" src="js-libs/jquery-1.7.js"></script>

    <style>
      <!--
      #test {
      width: 400px;
      height: 500px;
      }
      -->
    </style>
  </head>

  <body>

    <script type="text/javascript">
      $(function() {
        var w = 600,
            h = 350;

        var vis = d3.select("#test").append("svg:svg")
        .attr("width", w)
        .attr("height", h)
        .append("svg:g")
        .attr("transform", "translate(" + w / 2 + "," + h / 2 + ")");

        var g = vis.selectAll("g")
        .data([ { x:1 , y: 2} ])
        .enter().append("svg:g");

        g.append("svg:path")
        .attr("fill", "red")
        .attr("stroke", "red")
        .attr("stroke-width", "10")
        .attr("d", "M 100 350 l 150 -300")

        g.select("path")
        .on("click", function() { console.log("Hello"); });

        // XXX: how to execute click programmaticaly?
      })
    </script>

    <div id="test"></div>
  </body>
</html>

But doesn't work

I think we may use https://github.com/mbostock/d3/wiki/Internals#wiki-dispatch_on

But how to do it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

冬天的雪花 2025-01-05 22:43:49

不知道为什么,但 jQuery 和 d3 处理事件的方式似乎存在差异,导致 jQuery 引发的点击事件 $("#some-d3-element").click() 不分派到 d3 元素。

解决方法:

jQuery.fn.d3Click = function () {
  this.each(function (i, e) {
    var evt = new MouseEvent("click");
    e.dispatchEvent(evt);
  });
};

然后调用它:

$("#some-d3-element").d3Click();

not sure why, but there appears to be a discrepancy with the way jQuery and d3 handle events that causes a jQuery induced click event $("#some-d3-element").click() to not dispatch to the d3 element.

a workaround:

jQuery.fn.d3Click = function () {
  this.each(function (i, e) {
    var evt = new MouseEvent("click");
    e.dispatchEvent(evt);
  });
};

and then call it:

$("#some-d3-element").d3Click();
十秒萌定你 2025-01-05 22:43:49

只需调用 .on 方法作为注册值(即您的处理程序函数)的 getter,然后调用其结果:

g.select("path").on("click")();

如果您的处理程序使用绑定数据和/或事件字段,或者如果您绑定了多个事件侦听器(例如“click.thing1”和“click.thing2”)。在这种情况下,您可能最好使用 标准 DOM 方法

var e = document.createEvent('UIEvents');
e.initUIEvent('click', true, true, /* ... */);
g.select("path").node().dispatchEvent(e);

Simply call the .on method as a getter for the registered value (i.e. your handler function), then call the result of that:

g.select("path").on("click")();

It gets a little more complicated if your handler uses the bound data and/or event fields, or if you've got multiple event listeners bound (e.g "click.thing1" and "click.thing2"). In that case, you're probably best off just firing a fake event using the standard DOM methods:

var e = document.createEvent('UIEvents');
e.initUIEvent('click', true, true, /* ... */);
g.select("path").node().dispatchEvent(e);
溇涏 2025-01-05 22:43:49

对于D3 v4,您可能会需要这个:

d3.select('#some-id').dispatch('click');

参考:https:// github.com/d3/d3-selection#selection_dispatch

With D3 v4 you will likely want this:

d3.select('#some-id').dispatch('click');

Ref.: https://github.com/d3/d3-selection#selection_dispatch

坏尐絯 2025-01-05 22:43:49

这有效。我正在使用饼图,因此我选择所有“选定”饼图切片,并为每个饼图切片检索附加的“单击”回调(我已将其附加到此处未包含的另一部分代码中,使用 d3 的 . on() 方法),然后在正确的上下文中使用预期的参数进行调用。

d3.selectAll("g.selected").each(function(d, i) {
    var onClickFunc = d3.select(this).on("click");
    onClickFunc.apply(this, [d, i]);
});                

This works. I'm using pie charts, so I'm selecting all the "selected" pie slices, and for each of them, retrieving the attached "click" callback (that I have attached in another portion of code not included here, using d3's .on() method) and then invoking with the expected parameters in the correct context.

d3.selectAll("g.selected").each(function(d, i) {
    var onClickFunc = d3.select(this).on("click");
    onClickFunc.apply(this, [d, i]);
});                
以为你会在 2025-01-05 22:43:49

这个答案可能有点不相关 - 但希望对搜索如何调用 SVG 元素的单击事件的人有用 - 因为 jQuery $(mySvgElement).trigger("click") 不起作用。

这是您以编程方式触发/调用/引发 SVG 元素的单击事件的方式:

var ev = document.createEvent("SVGEvents");
ev.initEvent("click",true,true);

var target = $("svg>g>path[fill='#0011cc']").get(0); // get the SVG element here
target.dispatchEvent(ev);  // like $(target).trigger('click') - but working!

This answer might be somewhat unrelated - but hopefully useful to someone searching for how to invoke a click event of a SVG element - since jQuery $(mySvgElement).trigger("click") won't work.

This is how you would programmatically trigger/invoke/raise a click event for a SVG element:

var ev = document.createEvent("SVGEvents");
ev.initEvent("click",true,true);

var target = $("svg>g>path[fill='#0011cc']").get(0); // get the SVG element here
target.dispatchEvent(ev);  // like $(target).trigger('click') - but working!
似最初 2025-01-05 22:43:49

我来到这个线程寻找用于角度单元测试的 d3 mousemove 事件。

@natevw 的回答

g.select("path").on("click")();

对鼠标悬停事件有很大帮助。但是,将其应用于 mousemove 会产生 e.source null 错误。

解决方法是以编程方式设置 d3 事件。

d3.event = document.createEvent('MouseEvent');
d3.event.initMouseEvent("mousemove");
d3.select(elm[0]).select("rect").on("mousemove")();

希望这有帮助。

I came this thread looking for a d3 mousemove event for angular unit testing.

@natevw answer

g.select("path").on("click")();

helped a lot on mouseover event. But, applying that to mousemove was giving an e.source null error.

The work around was to set the d3 event programmatically.

d3.event = document.createEvent('MouseEvent');
d3.event.initMouseEvent("mousemove");
d3.select(elm[0]).select("rect").on("mousemove")();

Hope this helps.

黯淡〆 2025-01-05 22:43:49

您可以通过获取鼠标事件并向其传递 d3 将为您提供的参数来进行超级手动操作。这为您提供了一种相当干净的方法,同时仍然使用 d3 构造。对于单个元素,请使用以下内容:

var path = g.select('path');
path.on('click').call(path.node(), path.datum());

对于多个元素,您可以依次触发每个元素:

g.selectAll('path').each(function(d, i) {
  d3.select(this).on('click').apply(this, arguments);
});

如果您的选择器足够具体,或者如果您使用 .select() 而不是 .selectAll() 仅返回第一个元素。

You can go super manual by getting the mouse event and passing it the arguments that d3 would otherwise provide for you. This gives you a fairly clean way to do it while still using d3 constructs. For a single element use the following:

var path = g.select('path');
path.on('click').call(path.node(), path.datum());

For multiple elements, you can trigger each one in turn:

g.selectAll('path').each(function(d, i) {
  d3.select(this).on('click').apply(this, arguments);
});

The latter can also be used for a single element if your selector is specific enough, or if you use .select() instead of .selectAll() to only return the first element.

徒留西风 2025-01-05 22:43:49

@handler 的答案完全不适合我。它将单击 svg 元素,但不会注册其他模拟事件。这对我有用:

function eventFire(el, etype){
  if (el.fireEvent) {
    el.fireEvent('on' + etype);
  } else {
    var evObj = document.createEvent('Events');
    evObj.initEvent(etype, true, false);
    el.dispatchEvent(evObj);
  }
}

用法:

eventFire(document.getElementById(element_id), 'click');

@handler answer did not work for me entirely. It would click the svg element but additional simulated events would not register. This is what worked for me:

function eventFire(el, etype){
  if (el.fireEvent) {
    el.fireEvent('on' + etype);
  } else {
    var evObj = document.createEvent('Events');
    evObj.initEvent(etype, true, false);
    el.dispatchEvent(evObj);
  }
}

Usage:

eventFire(document.getElementById(element_id), 'click');
旧夏天 2025-01-05 22:43:49

我就是这样做的。

g.selectAll("path").on("click", function(d, i){
                                    my_function(d, i);
                                });

我发现回调可以与匿名函数一起使用。因此,对于上面的代码,单击的任何路径都将调用 my_function 并传入当前数据 d 和该路径的索引 i点击。

This is how I do it.

g.selectAll("path").on("click", function(d, i){
                                    my_function(d, i);
                                });

I've found the the callbacks work with anonymous functions. So for the code above, any path that is clicked will call my_function and pass in the current datum d and index i of the path that was clicked.

梦行七里 2025-01-05 22:43:49

我找到下一个解决方法:

d3.selectAll("path").each(function(d, i) {
                    onClickFunc.apply(this, [d, i]);
                });

其中 d 是数据,i 是该数据的索引

I find next workaround:

d3.selectAll("path").each(function(d, i) {
                    onClickFunc.apply(this, [d, i]);
                });

Where d is data and i is index this data

何其悲哀 2025-01-05 22:43:49

尝试 g.select("path").trigger("click")

Try g.select("path").trigger("click")

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文