Javascript 调用以变量命名的 jQuery 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8588307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:36:33  来源:igfitidea点击:

calling a jQuery function named in a variable

javascriptjqueryfunction

提问by bobighorus

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

我有几个 jQuery 函数,比如 function setOne(); setTwo(); setThree();

and a variable var numberthat values respectively "one", "two", "three".

以及var number分别取值“一”、“二”、“三”的变量。

How can I call function "setOne()" when number values "one", function "setTwo" when number values "two" and so on...?

当数值为“一”时如何调用函数“setOne()”,当数值为“2”时如何调用函数“setTwo”等等......?

Thank you so much in advance. Any help will be apreciated.

非常感谢你。任何帮助将不胜感激。

回答by andlrc

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

如果您的函数在全局范围内(在 window 对象上),您可以执行以下操作:

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

And using evalwill allow you to run functions in local scope:

使用eval将允许您在本地范围内运行函数:

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

When is JavaScript's eval()notevil?

JavaScript什么时候eval()不是邪恶的?

回答by Felix Kling

Create a name -> functionmap:

创建name -> function地图:

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

Then you call the function with:

然后你调用函数:

funcs[number]();

回答by Jose Rodrigues

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:

如果该变量详细说明了 JQuery 函数的实际名称,并且您想将该函数应用于 DOM 元素(如“body”),则可以执行以下操作:

 $('body')['function-name']('params');

回答by Yoshi

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

回答by I.G. Pascual

As simple as this is:

就这么简单:

function hello(){
    alert("hello");
}
var str = "hello";
eval(str+"()");

回答by OptimusCrime

Why do you have three functions for that?

为什么你有三个功能呢?

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

setNumber(1)will set number to 1

setNumber(1)将数字设置为 1

setNumber(2)will set number to 2

setNumber(2)将数字设置为 2

ect