I create a context-menu from an array like this:
var menu1 = [
{
'OPTION1':function(menuItem,menu) {
// code for OPTION1
}
},
{
'OPTION2':function(menuItem,menu) {
// code for OPTION2
}
}
];
When the user right-clicked on my webpage, a menu appears with开发者_Go百科 the options OPTION1 and OPTION2.
I need to change dynamically the function name, because it's the context-menu option text. Is there any way to declare the function name as a variable?
This is what I want:
var optionsletters = {};
optionsletters['option1'] = 'option_one';
optionsletters['option2'] = 'option_two';
var menu1 = [
{
optionsletters['option1']:function(menuItem,menu) {
// code for OPTION1
}
},
{
optionsletters['option2']:function(menuItem,menu) {
// code for OPTION2
}
}
];
EDIT#1: This is the plugin I've been using jQuery ContextMenu Plugin
EDIT#2: I need this to allow change language from spanish to english and viceversa.
You can't use the object literal notation to set arbritrary properties as you seem to try in the second example. This doesn't stop you from setting the property manualy:
function make_menu_item(name, func){
var item = {}; //Create an empty object
item[name] = func; //Assign the property with the name you choose
//(obj['option1'] is equivalent to obj.option1 in Javascript)
return item;
}
var menu = [
make_menu_item('option1', function () {...}),
make_menu_item('option2', function () {...})]
What about something like:
var name = 'option_one',
optionsletters = {};
optionsletters[name] = function() { ... };
Are you asking if you can change the key from 'OPTION1' : function() {} to 'option1' : function() {} ? If so you can just copy the function to a new variable onclick. If what you're asking is to be able to call something 'option1' as a string like option1 but actually call OPTION1(){} you can try a few different things. One you could make your array like so arr[{'name' : 'option1', 'func' : function(){} }] Then you could reference array[0].name and array[0].func.
With your current code it looks like you're blowing out your functions with strings.
JS is super expressive so there are a million ways to do anything. Functions are first-class objects so can be passed as parameters and even returned from functions.
精彩评论