javascript - 从字符串变量运行javascript函数并传递参数

标签 javascript jquery function jquery-callback

我需要从我的 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 标签属性中获取 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

关于javascript - 从字符串变量运行javascript函数并传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12491188/

相关文章:

javascript - 使用 JavaScript/jQuery 进行棘手的 Sprite 运动控制

javascript - 使用 Object.freeze() 扩展函数对象 - 无法添加字段

javascript - 使用下拉框仅显示选定的 div,但在未选择任何选项时显示所有 div

javascript - css 缩放的谷歌地图点击不正确的坐标

javascript - Bing map 版本 8。自定义缩放按钮

javascript - JavaScript 的正则表达式模式

javascript - js中的多个输入...?

MySQL 语法 - 变量的标准偏差,而不是列

r - 对在另一个函数中定义的函数使用相同的参数名称

oracle - nhibernate,Oracle中的调用函数,返回sys refcursor