سؤال

I am calling a JavaScript function like this:

window[className + 'Click']();

The className var contains some other string, in the end, it calls a function like myClick() or whatEverClick(). Thats alright, but is there a way to make the first part case insensitive?

Examples:
classname = whatever --> call whatEverClick()
classname = whatEver --> call whatEverClick()

Is that possible? Thanks!

هل كانت مفيدة؟

المحلول 2

Use this solution if it is absolutely necessary for you to execute in the context of Global object otherwise I prefer Solution 2(inspired by dystroy's answer)

Solution 1

if(window[className+"Click"]){
    window[className+'Click']();
}else{
    for(var f in window){
        if(window.hasOwnProperty(f) && typeof window[f]=='function'){
            if(f.toLowerCase() === className.toLowerCase()+'click'){
                window[f]();
            }
        }
    }
}

Solution 2

//Create an Object and store all the references
var functions_hash = {}

for(var f in window){
    if(window.hasOwnProperty(f) && typeof window[f]=='function'){
        functions_hash[f.toLowerCase] = window[f]
    }
}

//execute using the hash later on
functions_hash[className.toLowerCase()+'click']

نصائح أخرى

You probably shouldn't but you can (excluding the specificities of some languages) :

Step 1 : build a lowercase map of all window properties :

var map = {};
for (var key in window) map[key.toLowerCase()] = window[key];

Step 2 : call your function :

map[className.toLowerCase()+'click'](); 

If you want to call it with window as context (this), use

map[className.toLowerCase()+'click'].call(window); 

Demonstration

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top