[英]How to call a function with parameters from another function that has parameters?
我正在使用D3和JS。
我有一个创建按钮的函数,其中一个参数是onClick
,当单击按钮时(显然)它会运行。
例如:
simpleButton(imageURL, width, height, title, onClick){
.attr("xlink:href", imageUrl) //-original image
.attr( "width", width) //-icon width
.attr( "height", height) //-icon height
.on("click", onClick)
.append("svg:title")
.text(title); //-give the button a title
}
现在,我将使用我的一个按钮来隐藏一些形状(即,设置visibility:hidden
)。
所以我创建了另一个函数来隐藏选择,例如:
hideSelection(selection){
selection.classed("hidden", true);
}
此函数具有一个参数,以便我可以传递要隐藏的内容。
因此,例如我认为可行的内容如下所示:
simpleButton("\images\dog", 100, 100, "dog", hideSelection(dog));
现在,这确实可行,但无需我单击即可立即运行。 我知道这是因为由于括号-(),我立即调用了hideSelection
。
但是我的问题是,如何在运行它时立即停止调用此函数? 如何通过另一个带有参数的函数(如果有任何意义)运行带有参数的函数?
您应该将其包装在匿名函数中:
simpleButton("\images\dog",100,100, "dog", function() {
hideSelection(dog)
});
该函数可以访问dog
变量,因为它是一个闭包 -该函数在创建时可以访问父作用域。
实际上,您确实是在立即调用hideSelection(dog)
并将其结果传递给simpleButton
您需要传递对函数的引用 。 最简单的方法是将其包装在另一个函数中:
simpleButton("\\images\\dog", 100, 100, "dog", function() {
hideSelection(dog)
});
(PS您可能也想在图像路径中转义\\
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.