javascript d3.js,点击链接到另一个用变量编码的 URL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10569225/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
d3.js, click to link to another URL encoded with variables
提问by clerksx
I made a scatter plot, and want to add a link to each dot.
我做了一个散点图,并想为每个点添加一个链接。
chart.selectAll("scatter-dots")
.data(data)
.enter().append("circle")
.attr("cx", function (d) { return x(d.position[0]); } )
.attr("cy", function (d) { return y(d.position[1]); } )
.attr("r", 4)
.style("fill", "#666")
.style("opacity", 0.5)
.on("click", function(){
var url = "http://somelink.com/link.php?id=";
url += d.link_id;
//$(location).attr('href', url);
//window.location = url;
});
It works if I just put the pure String link such as window.location = "http://stackoverflow.com" However, if I add queries to the end of the URL from a variable, the page does not redirected.
如果我只放置纯字符串链接,例如 window.location = "http://stackoverflow.com" ,它就可以工作。但是,如果我从变量向 URL 末尾添加查询,则页面不会重定向。
Neither jquery nor javascript worked (as commented.)
jquery 和 javascript 都不起作用(如评论所示。)
I also tried an external js file, still fail.
我也试过外部js文件,还是失败。
This is in a PHP file, if this helps.
这是在一个 PHP 文件中,如果有帮助的话。
回答by methodofaction
If it works with a static string then something is wrong with d.link_id. Try seeing what's inside either by doing alert(d.link_id)
or if you use a firebug or similars do console.log(d.link_id)
.
如果它适用于静态字符串,则 d.link_id 有问题。尝试通过执行alert(d.link_id)
或使用萤火虫或类似方法来查看内部内容console.log(d.link_id)
。
Alternatively, you should use real anchors for linking your nodes instead of setting click events. This would go something like...
或者,您应该使用真正的锚点来链接您的节点,而不是设置点击事件。这将类似于...
chart.selectAll("scatter-dots")
.data(data)
.enter()
.append("a")
.attr("xlink:href", function(d) {return "http://somelink.com/link.php?id=" + d.link_id})
.append("circle")
.attr("cx", function (d) { return x(d.position[0]); } )
.attr("cy", function (d) { return y(d.position[1]); } )
.attr("r", 4)
.style("fill", "#666")
.style("opacity", 0.5)
(I can't seem to recall if this is the exact way of doing it, you might need to save the anchors in a variable and then append the circles to them.)
(我似乎不记得这是否是这样做的确切方法,您可能需要将锚点保存在变量中,然后将圆圈附加到它们。)