【发布时间】:2012-09-19 08:41:24
【问题描述】:
我需要从我的 costom jquery 插件中调用用户定义的 javascript 函数并将参数传递给它,例如:
function test(data)
{
var myfunc="function(data){alert(data);}"; //this is user defined function I retrieved from html tag attribute
var fn=new Function("("+myfunc+")();");
fn.apply(this,arguments);
return fn;
}
test("hello");
结果未定义,如何将数据参数从测试函数传递到用户定义函数?提前致谢!
问题更新:
我正在写一个jquery插件来处理ajax请求,很像asp.net mvc unobtrusive ajax,我从html标签attrbute得到ajax callfack函数,例如:
<div data-ajax-success="function(data,status,xhr){alert(data);}"....
data-ajax-success 属性的值是用户定义的函数,可以是以下格式:
data-ajax-success="function(data,status,xhr){alert(data);}"
data-ajax-success="function(data){alert(data);}"
data-ajax-success="function(){alert('hello');}"
data-ajax-success="functionName"
我需要将此属性值解析为javascript函数并将jquery ajax回调参数传递给该函数,其中data-ajax-success值为函数名称,我可以使用Micrsoft jquery-unobtrusive-ajax中定义的以下方法正确调用它.js:
function getFunction(code, argNames) {
var fn = window, parts = (code || "").split(".");
while (fn && parts.length) {
fn = fn[parts.shift()];
}
if (typeof (fn) === "function") {
return fn;
}
argNames.push(code);
return Function.constructor.apply(null, argNames);
}
但是当 data-ajax-success 是函数体时,我无法将参数传递给它,这是我处理 ajax 回调的示例代码:
loadData: function (index, options) {
complete: function (xhr,status) {
$(context.loading).hide(context.loadingDuration);
getFunction(context.onComplete, ["xhr", "status"]).apply(this, arguments);
},
success:function (data, status, xhr) {
$(context.updateTarget).html(data);
getFunction(context.onSuccess, ["data", "status", "xhr"]).apply(this, arguments);
},
error: getFunction(context.onFailure, ["xhr", "status", "error"])
});
$.ajax(options);
}
有人可以帮助我吗?非常感谢!
【问题讨论】:
-
您能更详细地解释一下字符串
"function(data){alert(data);}"的来源吗? -
this 有帮助吗? (使用
eval) -
我能否首先指出总体而言,这看起来是个非常糟糕的主意,您可能做错了。
标签: javascript jquery function jquery-callback