I am attempting to figure out what element is creating an on click event in d3. Here is some sample code that I am using to test event handling:
我试图找出在d3中创建一个on click事件的元素。以下是我用于测试事件处理的一些示例代码:
g.selectAll("text")
.data(allPoints).enter()
.append("text")
.attr("text-anchor", "end")
.attr("class", "point-label")
.attr("font-size", fontSize)
.attr("cursor","pointer")
.attr("id", function(d,i){
return allPointData[allPoints.indexOf(d)][1] + "_name";
})
.text( function(d) { return allPointData[allPoints.indexOf(d)][1]; })
.on("click", function(d) {
// figure out what DOM element raised me
});
So far, I have tried to do this:
到目前为止,我试图这样做:
.on("click", function(d) {
alert("########### text with " + JSON.stringify(d3.event.target));
});
However, I am getting a weird value back with some data from the actual dom object, as opposed to the entire object itself.
但是,我从实际的dom对象获得了一些奇怪的值,而不是整个对象本身。
########### text with {"__data__":[-122.2405556,37.7652778]}
UPDATE: When I try : JSON.stringify(this) , I also get the same object
更新:当我尝试:JSON.stringify(this)时,我也得到了相同的对象
In reality, all that I am trying to do is figure out what element was called, and hopefully grab its ID. With this, I want to run some js code in my Scartchpad in firefox, to try and manually invoke the click function with actual code like:
实际上,我所要做的就是找出所谓的元素,并希望获取它的ID。有了这个,我想在firefox中的Scartchpad中运行一些js代码,尝试用实际代码手动调用click函数,如:
document.getElementById("#element").click()
1 个解决方案
#1
2
You can figure out the calling DOM object using this
:
您可以使用以下方法找出调用DOM对象:
.on("click", function(d) {
console.log("my name is " + d3.select(this).text() +
" and my ID is " + d3.select(this).attr("id"));
});
Here is a fiddle: https://jsfiddle.net/ap1m1L0q/1/
这是一个小提琴:https://jsfiddle.net/ap1m1L0q/1/
#1
2
You can figure out the calling DOM object using this
:
您可以使用以下方法找出调用DOM对象:
.on("click", function(d) {
console.log("my name is " + d3.select(this).text() +
" and my ID is " + d3.select(this).attr("id"));
});
Here is a fiddle: https://jsfiddle.net/ap1m1L0q/1/
这是一个小提琴:https://jsfiddle.net/ap1m1L0q/1/