我是
javascript的新手,目前正努力在尝试进行d3选择时选择此对象.我做了以下示例,我正在调用一个函数,以及一个on mousemove事件:
function changeFont() {
d3.select(this)
.attr('font-size','2em')
}
...
.on('mousemove',function() {
var mouse = d3.mouse(this);
var xVal = mouse[0];
// this would work,but not when its called in a function
// d3.select(this)
// .attr('font-size','2em')
// this works
d3.select(this)
.attr("opacity",1)
// this doesnt
changeFont()
});
在我未在此处显示的主脚本中,我通过编写处理每个mousemove,mouSEOver等效果的函数来组织我的代码.但是由于这些功能,我遇到了这个问题,我无法在鼠标悬停功能中进行d3.select(this)…对于我应该采取哪些不同的做法?
我应该将此作为参数传递给我的changeFont()函数吗?或者我应该以不同的方式访问它?
谢谢!
解决方法
虽然安德鲁的
answer可能是最合适的,如果你从字面上理解问题,我想加上我的两分钱.你真正的问题似乎不是要抓住这个,而是反复访问该元素以应用你的操作.由于摆弄这可能是JavaScript的痛苦,因此可能值得通过直接传递选择而采用稍微不同的方法.这也将提高性能,因为无需一遍又一遍地重新选择.
首先,让我们稍微重构你的changeFont()函数来接受一个选择对象.
function changeFont(selection) {
selection
.attr('font-size','2em');
}
注意,这是如何使函数更普遍适用的,因为它不会对传递给它的选择做出任何假设.它可能是你的d3.select(this),一个包含多个元素或任何其他D3选择对象的选择.此外,您不需要保留以前的此范围.
调用此函数基本上有两种方法.
>当调用函数时,显而易见的将直接将选择作为参数传递:
const d3This = d3.select(this); changeFont(d3This);
>幸运的是,有一种更优雅的方式,通过使用D3自己的selection.call(),如果你需要在同一个选择上进行多次调用,它甚至允许方法链接.
function changeFont(selection) { selection.attr("font-size","2em"); }
function changeFill(selection) { selection.attr("fill","limegreen"); }
function changeOpacity(selection) { selection.attr("opacity","0.1"); }
// ...
.on("mouSEOver",function() {
// Call the functions for this element.
d3.select(this)
.call(changeFont)
.call(changeFill)
.call(changeOpacity);
// Instead,you Could also apply the same pattern to all texts.
d3.selectAll("text")
.call(changeFont)
.call(changeFill)
.call(changeOpacity);
}