簡體   English   中英

從字符串變量運行javascript函數並傳遞參數

[英]run javascript function from string variable and pass parameters

我需要從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不顯眼的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);
  }

有人可以幫助我嗎? 非常感謝你!

MDN像下面這樣描述Function對象的語法:

new Function ([arg1[, arg2[, ... argN]],] functionBody)

這是相應的示例:

// Example can be run directly in your JavaScript console

// Create a function that takes two arguments and returns the sum of those arguments
var adder = new Function("a", "b", "return a + b");

// Call the function
adder(2, 6);
// > 8

應用於示例代碼時,它應顯示為:

var fn=new Function("data",myfunc);

參考:

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function

您沒有將參數傳遞給fn函數。

更改此部分:

var fn=new Function("("+myfunc+")();");

對此:

var fn=new Function("("+myfunc+")("+data+");");

但是,如果要像這樣定義函數,則data變量必須包含json字符串:

var fn=new Function("("+myfunc+")("+JSON.stringify(data)+");");

我通過修改此microsoft方法解決了它:

  function getFunction(code, argNames) {
    var fn = window, parts = (code || "").split(".");
    while (fn && parts.length) { fn = fn[parts.shift()]; }
    if (typeof (fn) === "function") { return fn; } //onSuccess="functionName"
    if ($.trim(code).toLowerCase().indexOf("function")==0) { return new Function("return (" + code + ").apply(this,arguments);");} //onSuccess="function(data){alert(data);}"
    argNames.push(code);
    try {return Function.constructor.apply(null, argNames); //onSuccess="alert('hello');return false;"
    }catch(e){alert("Error:\r\n"+code + "\r\nis not a valid callback function");}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM