I have a class like this
$.fn.dimeBar = function(custom) {
var var1 = 'test1';
var var2 = 'test2';
if(sometest){
//how can i access var1 or var2 here by using string开发者_如何学Go name of variables
//some thing like alert(this['var1']) --> should alert: 'test1'
}
}
Try something like:
$.fn.dimeBar = function(custom) {
var options = {
var1: 'test1',
var2: 'test2'
};
if(sometest){
var foo = 'var1';
alert(options[foo]); // "test1"
}
};
Alternatively, this may be a bit more inline with the jQuery Plugin Development Pattern
(function($){
$.fn.dimeBar = function(options){
// defaults
options = $.extend({
var1: "default",
var2: "hello world"
}, options);
// debug options
$.each(options, function(key, value){
console.log(key+' is set to'+value);
});
};
})(jQuery);
$('#foo').dimeBar({var2: "hello kitty"});
// console output
// var1 is set to default
// var2 is set to hello kitty
You would just use: ....
if (sometest) { alert(var1); } ....
Since you declared the vars before the if statement, they will be available from within it.
If you are worried about scope, if it's within an object, you would use: alert(this.var1);
精彩评论