我正在尝试这样做(也在 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
但是怎么做呢?
最佳答案
不知道为什么,但 jQuery 和 d3 处理事件的方式似乎存在差异,导致 jQuery 引发点击事件 $("#some-d3-element").click()
不分派(dispatch)到 d3 元素。
解决方法:
jQuery.fn.d3Click = function () {
this.each(function (i, e) {
var evt = new MouseEvent("click");
e.dispatchEvent(evt);
});
};
然后调用它:
$("#some-d3-element").d3Click();
关于javascript - 如何在 d3 中以编程方式调用 "click"事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36224663/