d3.select(this) works on mouseover, but not on function called in mouseover

前端 未结 3 1914
感情败类
感情败类 2021-02-05 23:29

I am new to javascript and currently struggling with selecting the this object while trying to do a d3 selection. I\'ve made the following example, with a funct

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-05 23:55

    Just for completeness, since this question has already two very good answers: you can avoid the confusion with this if you use the third and second arguments combined. That's something that even D3 developers forget eventually.

    In several D3 methods, the current DOM element is just the current index of the nodes' group. So, in the anonymous function...

    .on("mouseover", function(_, i, n) {
    

    ... this is just n[i], which you can just pass to the other functions. The _ here corresponds to the first argument, the datum: I'm using _ just to follow the convention that shows this argument is not used.

    The nice thing about this approach is that you can even (for whatever reasons you have) use arrow functions:

    d3.select("body").selectAll(null)
      .data(["foo", "bar", "baz"])
      .enter()
      .append("p")
      .text(String)
      .on("mouseover", (_, i, n) => {
        changeFont(n[i])
      });
    
    function changeFont(element) {
      d3.select(element).style("font-size", "2em")
    }

    Of course, you can't get the DOM element using this inside the arrow function.

提交回复
热议问题