jquery动态函数
我只需要逻辑和理解如何做到这一点。
问题:
我有几个非常相似的函数,但我想动态创建/调用
示例:
$(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');
}
});
如何传入 foo/bar 来创建函数?伪代码
$(document).ready(function() {
// would pass foo/bar to this?
$($x)(function() {
$("#"+$(this)+"_elem").toggle(true).attr('required', true);
alert('This is '+$(this));
});
});
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 the 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));
});
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您想动态调用 foo 或 bar 吗?
处于高水平。不过,在您的实例中,您要求将该符号用作选择器中的变量:
如果您想将其既用作字符串值又用作方法名称,则可以评估该符号以获取该方法:
You want to dynamically call foo or bar?
At a high level. In your instance, though, you're asking to use that symbol as just a variable in your selector:
If you want to use it both as a string value, and the method name, you can eval the symbol to get the method:
我不确定我是否完全理解你的问题,但是你想根据一些参数动态创建一个函数吗?如果是这样,您可以执行以下操作:
然后
make_func('foo')
将返回一个与原始示例中的函数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:
Then
make_func('foo')
would return a function which is equivalent to the functionfoo
in your original example.