I just need the logic and understanding on how I can do this.
The problem:
I have several functions that are very similar but I want to create/call th开发者_JS百科e dynamically
Example:
$(document).ready(function() {
function foo() {
$("#foo_elem").toggle(true).attr('required', true);
alert('This is foo');
}
function bar() {
$("#bar_elem").toggle(true).attr('required', true);
alert('This is bar');
}
});
How can I pass in foo/bar to create the function? Pseudo code
$(document).ready(function() {
// would pass foo/bar to this?
$($x)(function() {
$("#"+$(this)+"_elem").toggle(true).attr('required', true);
alert('This is '+$(this));
});
});
You want to dynamically call foo or bar?
function callMethod(method)
{
method();
}
callMethod(foo); // foo is the symbol for your method
callMethod(bar); // etc
At a high level. In your instance, though, you're asking to use that symbol as just a variable in your selector:
function callMethod(elementPrefix)
{
$('#' + elementPrefix+ '_elem').toggle(true).attr('required', true);
alert('This is ' + elementPrefix);
}
If you want to use it both as a string value, and the method name, you can eval the symbol to get the method:
var methodName = 'foo';
var text = 'This is ' + methodName; // This is foo
var method = eval('(' + methodName + ')');
method(); // calls foo()
I'm not sure if I understood your question fully, but do you want to dynamically create a function based on some arguments? If so, you could do something like this:
function make_func(x) {
return function() {
$("#"+x+"_elem").toggle(true).attr('required', true);
alert('This is '+x);
};
}
Then make_func('foo')
would return a function which is equivalent to the function foo
in your original example.
精彩评论