我正在尝试(也在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>Run Code Online (Sandbox Code Playgroud)
但是不起作用
我想我们可以使用https://github.com/mbostock/d3/wiki/Internals#wiki-dispatch_on
但怎么办呢?
han*_*ler 83
不知道为什么,但似乎与jQuery和d3处理事件的方式存在差异,导致jQuery引发的click事件$("#some-d3-element").click()不会分派到d3元素.
解决方法:
jQuery.fn.d3Click = function () {
this.each(function (i, e) {
var evt = new MouseEvent("click");
e.dispatchEvent(evt);
});
};
Run Code Online (Sandbox Code Playgroud)
然后调用它:
$("#some-d3-element").d3Click();
Run Code Online (Sandbox Code Playgroud)
nat*_*evw 68
只需将该.on方法作为注册值的getter(即您的处理函数)调用,然后调用该结果:
g.select("path").on("click")();
Run Code Online (Sandbox Code Playgroud)
如果您的处理程序使用绑定数据和/或事件字段,或者如果您绑定了多个事件侦听器(例如"click.thing1"和"click.thing2"),则会变得更复杂一些.在这种情况下,您可能最好只使用标准DOM方法触发假事件:
var e = document.createEvent('UIEvents');
e.initUIEvent('click', true, true, /* ... */);
g.select("path").node().dispatchEvent(e);
Run Code Online (Sandbox Code Playgroud)
Jon*_*ker 16
使用D3 v4,您可能会想要这样:
d3.select('#some-id').dispatch('click');
Run Code Online (Sandbox Code Playgroud)
参考:https://github.com/d3/d3-selection#selection_dispatch
And*_*ank 14
这有效.我正在使用饼图,所以我选择所有"选定的"饼图片,并为每个片段检索附加的"点击"回调(我已经附加在此处未包含的代码的另一部分,使用d3). on()方法)然后在正确的上下文中使用预期的参数进行调用.
d3.selectAll("g.selected").each(function(d, i) {
var onClickFunc = d3.select(this).on("click");
onClickFunc.apply(this, [d, i]);
});
Run Code Online (Sandbox Code Playgroud)
这个答案可能有点无关 - 但希望对搜索如何调用 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!
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
46898 次 |
| 最近记录: |