我只需要逻辑和理解我如何做到这一点.
问题:
例:
$(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()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。