我需要調用定義的JavaScript功能的用戶從我的德,崔根源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不顯眼的阿賈克斯,我得到的HTML標籤attrbute阿賈克斯callfack功能,例如:
<div data-ajax-success="function(data,status,xhr){alert(data);}"....
是用戶定義的數據Ajax的成功屬性的值的功能,它可以是以下格式:
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"
我需要解析此屬性值作爲javascri PT功能,並通過jQuery的Ajax回調參數傳遞給該函數,其中數據Ajax的成功值是函數的名字,我能正確使用項目建立在微軟jQuery的不顯眼,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);
}
但當數據Ajax的成功是函數體,我不能錯過參數給它,下面是處理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);
}
任何人都可以幫我嗎?非常感謝你!
你能更緊密地解釋其中的字符串'「功能(數據){警報(數據);} 「'來自,到底? – Tomalak
[this](http://stackoverflow.com/questions/2060634/jquery-string-to-function-convert)有幫助嗎? (使用'eval') – keyser
我可以首先指出,總體而言,這看起來是一個非常糟糕的主意,你可能做錯了。 – nickf