我知道这个问题以前可能被问过,但我无法正确理解或实现列出的解决方案。我正在尝试创建如下所示的自定义确认框:
// This is what a Dialog looks like
var dialogMessage = {
head: 'Dialog Heading',
body: 'Dialog Message Body',
yah: function(parameter){ something(parameter); },
nah: function(parameter){ somethingElse(parameter); }
};
// This is how the confirm boxes are created and output to the user
function confirm(Dialog){
// Render code goes here
/*
Here, we listen to see if the OK button is clicked.
If so, we execute the defined yah() function
*/
$("button.OK").click(function(){
if( typeof( Dialog.yah ) === "function" ){
Dialog.yah();
}
});
/*
Here, we listen to see if the Cancel button is clicked.
If so, we execute the defined nah() function
*/
$("button.cancel").click(function(){
if( typeof( Dialog.nah ) === "function" ){
Dialog.nah();
}
});
}
// This is how we use the function
confirm( dialogMessage );
基本上我想知道的是如何在Dialog.yah
和Dialog.nah
函数中正确传递参数,以便函数体可以正确使用它们。
就像其他正常函数一样。
Dialog.yah("OK");
...
Dialog.nah("NOOOOOOOOOOOOOO");
此外,您不必仅仅为了调用其他函数而创建函数包装器。您可以像这样简单地将它们作为对象中的值
var dialogMessage = {
head: 'Dialog Heading',
body: 'Dialog Message Body',
yah: something,
nah: somethingElse
};
现在,Diaglog.yah
和something
是一回事。因此,您正在间接调用something
。
编辑:正如我从评论中了解到的那样,您在知道传递给函数的参数时遇到问题。
比方说,您正在调用Dialog.yah
它实际上是函数something
。然后,您可以使用这样的arguments
设计something
function something() {
var param1 = arguments[0], param2 = arguments[1]...;
}
该函数可以接受任意数量的参数,但不必在签名中显式提及它们。如果接受的参数数少于预期,则函数可能会决定抛出错误。