gpt4 book ai didi

javascript - 为什么我的拖动函数中 d、this 和变量都未定义?

转载 作者:行者123 更新时间:2023-12-03 08:30:03 26 4
gpt4 key购买 nike

我试图在拖动时根据矩形的坐标执行一些逻辑。我想选择矩形内的所有圆圈。

function dragmove(d) {
var barz = document.querySelector("#visual");

var point = d3.mouse(barz),
tempP = {
x: point[0],
y: point[1]
};

d3.event.sourceEvent.stopPropagation();

d3.select(this).style({
opacity: 0.05
})
console.log(selectionBox.x); //turns out undefined
console.log(d.x); //also undefined
console.log(d3.select(this)); //undefined

vis.selectAll("circle").filter(function (d, i) {
return (d.x > d3.select(this).x && d.x < (d3.select(this).x + d3.select(this).width))
}).style({
opacity: 0.1
});

如果您还没有注意到,现在我只在 x 坐标内检查它,至少在我完成修复之前是这样。 Here's the fiddle.

每当我尝试运行它时,它都不会出现任何错误,但它无法按预期工作,因为引用未定义。有什么原因导致所有引用资料都不起作用吗?

要重现此效果,您需要首先在 Canvas 上拖动以绘制一个矩形,然后拖动该矩形

最佳答案

你的原始函数似乎不太正确。我尝试了 this answer 中的一个

var drag = d3.behavior.drag()
.origin(function(d) {
var t = d3.select(this);
return {x: t.attr("x"), y: t.attr("y")};
})
.on("dragstart", dragstarter)
.on("drag", dragmove);

现在它向dragmove函数传递一个有效的对象。

在下面的代码中:

vis.selectAll("circle").filter(function (d, i) {
return (d.x > d3.select(this).x && d.x < (d3.select(this).x + d3.select(this).width))
})...

this 的引用未定义,因为 Array.prototype.filter功能有效。根据规范,我们可以提供自己的 this 作为过滤函数的第二个参数,因此:

vis.selectAll("circle").filter(function (d, i) {
return (d.x > d3.select(this).x && d.x < (d3.select(this).x + d3.select(this).width))
}, this)...

Updated your fiddle

关于javascript - 为什么我的拖动函数中 d、this 和变量都未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33380794/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com