jquery: use string as function (error: string is not a function)

This question already has an answer here:

  • How to execute a JavaScript function when I have its name as a string 29 answers
  • How to turn a String into a JavaScript function call? [duplicate] 13 answers

  • It depends a bit on the scope, but the general idea is that you can use the square bracket notation to get a reference to the function and execute it. For example, the following:

    window[value]();
    

    would be equivalent to callme() for the first iteration, assuming the callme function is globally scoped (a property of the window object).


    You could try using eval to evaluate the string as a function, although you have to be careful security-wise. Evaluating a string coming from user input or a form submission could make your site vulnerable to cross-site scripting and session hijacking.

    Example:

    eval(value + "();"); //call "value" as a function
    
    链接地址: http://www.djcxy.com/p/94828.html

    上一篇: 抛出包含变量名称的异常

    下一篇: jquery:使用字符串作为函数(错误:字符串不是一个函数)