最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - pass arguments to a d3 on "click" event callback - Stack Overflow

programmeradmin3浏览0评论

Here is my code:

function toggleClass(element, className){
  d3.select(element).classed(className, !d3.select(element).classed(className));
}

d3.selectAll("rect").on("click", toggleClass(this, "clicked");

I cannot get it to work, it appears that passing arguments to a DOM event is bad news bears. Does anyone know a work-around for this?

Thank you

Here is my code:

function toggleClass(element, className){
  d3.select(element).classed(className, !d3.select(element).classed(className));
}

d3.selectAll("rect").on("click", toggleClass(this, "clicked");

I cannot get it to work, it appears that passing arguments to a DOM event is bad news bears. Does anyone know a work-around for this?

Thank you

Share Improve this question asked Aug 1, 2014 at 21:57 rowyourboatrowyourboat 3411 gold badge4 silver badges14 bronze badges 2
  • 1 You can use an anonymous function to do this: .on('click', function() { toggleClass(this, "clicked"); }) – jshanley Commented Aug 1, 2014 at 22:00
  • 2 Arguments are always evaluated before they are passed to a function. So if you have foo(bar()), then bar is executed first and its return value is passed to foo. If you want to pass a callback, you have to pass a function, not call a function. – Felix Kling Commented Aug 1, 2014 at 22:04
Add a ment  | 

2 Answers 2

Reset to default 11

This works:

function toggleClass(element, className){
  d3.select(element).classed(className, !d3.select(element).classed(className));
}

d3.selectAll("rect").on("click", function () {
  toggleClass(this, "clicked");
});

here is the working fiddle: http://jsfiddle/g45Ju/

thanks to jshanley

Have you tried selection.datum() function? This snippet might give you an idea :

d3
 .select('svg')
 .append('circle')
 .datum({
    'x':10,
    'y':100,
    'z':100
  })
 .on('click'),function(d){
     //Here d = {'x':10,'y':100,'z':1000}
  });
发布评论

评论列表(0)

  1. 暂无评论