我正在使用 D3.js 创建一个图表,如这个简化示例中所述
class MyClass {
// logic goes here
// constructor() and other functions defined here.
doSomething() {
console.log('something.');
}
}
function createChart(chartID, data) {
// creating the SVG and appending it to the body
var svg = d3.select('body').append('svg')
.attr('width',400)
.attr('height',400)
.attr('id',chartID);
// instantiating an instance of MyClass to be attached to the SVG
var anObject = new MyClass();
svg.myObject = anObject; // this has no effect
// code to actually build the chart + math to be done on passed data
// finally, attach a click event to the svg so that data can be manipulated later on
svg.on('click',function(){
var object = d3.select(this).myObject; //this does not work
object.doSomething(); // so this also doesn't work
});
}
createChart('test1',[1,2,3,4]); // triggering the createChart() function
我假设变量 svg
被视为任何 JSON 对象,因此,我认为我可以将任何对象附加到它。
显然,事实并非如此。我怎样才能将对象附加到 HTML DOM 元素,以便以后可以访问该对象?
最佳答案
svg
变量是一个包含 DOM 元素的 d3 选择对象。
您可以设置 svg 的 datum()
并稍后检索它
function createChart(chartID, data) {
// creating the SVG and appending it to the body
var svg = d3.select('body').append('svg')
.attr('width',400)
.attr('height',400)
.attr('id',chartID);
// instantiating an instance of MyClass to be attached to the SVG
var anObject = new MyClass();
svg.datum(anObject);
// code to actually build the chart + math to be done on passed data
// finally, attach a click event to the svg so that data can be manipulated later on
svg.on('click',function(){
var object = d3.select(this).datum();
object.doSomething();
});
}
或者使用 click
处理程序中的 this
是 DOM 元素这一事实
function createChart(chartID, data) {
// creating the SVG and appending it to the body
var svg = d3.select('body').append('svg')
.attr('width',400)
.attr('height',400)
.attr('id',chartID);
// instantiating an instance of MyClass to be attached to the SVG
var anObject = new MyClass();
svg.node().myObject = anObject;
// code to actually build the chart + math to be done on passed data
// finally, attach a click event to the svg so that data can be manipulated later on
svg.on('click',function(){
var object = this.myObject;
object.doSomething();
});
}
关于javascript - 如何将动态对象附加到 HTML 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51595785/