我需要从我的 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);
}
任何人都可以帮助我吗?非常感谢!