简体   繁体   English

调用JS变量内的值作为JS函数名称

[英]call value inside a JS variable as a JS function name

Hello I have a function to perform actions but name of the function is inside a variable... 您好,我有一个执行动作的函数,但函数名称在变量内...

below code will get the URL's hashed part example: #JHON and remove # and store it inside URLHASH variable..example: JHON 下面的代码将获取URL的哈希部分示例:#JHON并删除#并将其存储在URLHASH变量中。

  var urlhash = document.location.hash;
  urlhash = urlhash.replace(/^.*#/, '');

always there is a function name from that value inside variable and i want to call value inside that variable as a function name 总是在变量内的值中有一个函数名,而我想将该变量内的值作为函数名调用

  window.onload=function() {
    Value inside URLHASH variable should run as a name of a variable. example: jhon();
  };

Is it possible ? 可能吗 ? I tried some codes but it calls variable name as a function not value inside the variable..help me.. 我尝试了一些代码,但它将变量名称作为函数而不是变量内部的值调用..帮助我..

You can use the following: 您可以使用以下内容:

window[urlhash]();

This will invoke a function whose name is the value of the urlhash variable, defined in the context of window . 这将调用一个函数,该函数的名称是在window上下文中定义的urlhash变量的 Here's a DEMO . 这是一个DEMO

You can access attributes of objects as if they are array indexes, so for example, you could run getElementById this way: 您可以像访问数组索引一样访问对象的属性,例如,可以通过以下方式运行getElementById

document["getElementById"]("#myid");

so& if you know beforehand of which object the function will be a member, you can access it this way. 这样,如果您事先知道函数将成为哪个对象的成员,则可以通过这种方式访问​​它。 functions in the global scope are methods of the window object. 全局范围内的函数是window对象的方法。 However, if the hash may contain expressions like #document.write() , you would have to do some parsing. 但是,如果散列可能包含#document.write()类的表达式,则必须进行一些解析。 it could work like this 它可以像这样工作

window.onload=function() {
    var urlhash = document.location.hash, current_element = window;
    urlhash = urlhash.replace(/^.*#/, '');
    elements = urlhash.split(".");
    for(var i=0; i<elements.length; i++){
        current_element = current_element[elements[i]];
    }
    //execute the actual function
    current_element();
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM