calling a jQuery function named in a variable

前端 未结 6 723
小蘑菇
小蘑菇 2020-12-10 01:21

I have several jQuery function like function setOne(); setTwo(); setThree();

and a variable var number that values respectively \"one\", \

相关标签:
6条回答
  • 2020-12-10 01:55

    If you have your function in the global scope (on the window object) you can do:

    // calls function setOne, setTwo, ... depending on number.
    window["set" + number](); 
    

    And using eval will allow you to run functions in local scope:

    eval("set" + number + "()");
    

    When is JavaScript's eval() not evil?

    0 讨论(0)
  • 2020-12-10 01:57

    If the variable details the actual name of the JQuery function and you want to apply the function to a DOM element like 'body', you can do the following:

     $('body')['function-name']('params');
    
    0 讨论(0)
  • 2020-12-10 02:03

    As simple as this is:

    function hello(){
        alert("hello");
    }
    var str = "hello";
    eval(str+"()");
    
    0 讨论(0)
  • 2020-12-10 02:06

    Why do you have three functions for that?

    var number;
    function setNumber(n) {
        number = n;
    }
    

    setNumber(1) will set number to 1

    setNumber(2) will set number to 2

    ect

    0 讨论(0)
  • 2020-12-10 02:07

    Create a name -> function map:

    var funcs = {
        'one': setOne,
        'two': setTwo
        /*...*/
    };
    

    Then you call the function with:

    funcs[number]();
    
    0 讨论(0)
  • 2020-12-10 02:18

    Provided your functions are in the global scope, try:

    function setOne() {
      console.log('setOne called');
    }
    function setTwo() {
      console.log('setTwo called');
    }
    function setThree() {
      console.log('setThree called');
    }
    
    var number, funcName;
    
    number = 'one';
    funcName = 'set' + number.charAt(0).toUpperCase() + number.slice(1);
    window[funcName](); // output: setOne called
    
    number = 'two';
    funcName = 'set' + number.charAt(0).toUpperCase() + number.slice(1);
    window[funcName](); // output: setTwo called
    
    number = 'three';
    funcName = 'set' + number.charAt(0).toUpperCase() + number.slice(1);
    window[funcName](); // output: setThree called
    
    0 讨论(0)
提交回复
热议问题