我只需要逻辑和理解我如何做到这一点.
问题:
例:
$(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'); } });
$(document).ready(function() { // would pass foo/bar to this? $($x)(function() { $("#"+$(this)+"_elem").toggle(true).attr('required',true); alert('This is '+$(this)); }); });
解决方法
你想动态调用foo或bar?
function callMethod(method) { method(); } callMethod(foo); // foo is the symbol for your method callMethod(bar); // etc
在很高的水平.但是,在您的实例中,您要求将该符号用作选择器中的变量:
function callMethod(elementPrefix) { $('#' + elementPrefix+ '_elem').toggle(true).attr('required',true); alert('This is ' + elementPrefix); }
如果要将其用作字符串值和方法名称,则可以使用符号来获取方法:
var methodName = 'foo'; var text = 'This is ' + methodName; // This is foo var method = eval('(' + methodName + ')'); method(); // calls foo()