如何通过 jQuery 中的 SetTimeout 函数传递元素 ID?
我想通过下面的函数传递 id1、id2 和 id3。这工作得很好:
function doSomething(id1,id2,id3) {
$(id1).fadeIn('slow',.25);
$(id1).fadeIn('slow',.25);
$(id1).fadeIn('slow',.25);
};
但这不起作用:
function doSomething(id1,id2,id3) {
setTimeout( " $(id1).fadeIn('slow',.25) ", 300);
setTimeout( " $(id1).fadeIn('slow',.25) ", 300);
setTimeout( " $(id1).fadeIn('slow',.25) ", 300);
};
我如何让第二个工作?我的想法是我需要在 id 周围添加一些标点符号。或者我可以在 setTimeout 括号内为函数设置一个变量。有什么想法吗?
I want to pass id1, id2 and id3 through the function below. This works just fine:
function doSomething(id1,id2,id3) {
$(id1).fadeIn('slow',.25);
$(id1).fadeIn('slow',.25);
$(id1).fadeIn('slow',.25);
};
But this does not work:
function doSomething(id1,id2,id3) {
setTimeout( " $(id1).fadeIn('slow',.25) ", 300);
setTimeout( " $(id1).fadeIn('slow',.25) ", 300);
setTimeout( " $(id1).fadeIn('slow',.25) ", 300);
};
How do I get the second one to work? My thought is I need some punctuation around the id's. Or perhaps I can set a variable for the function within the setTimeout brackets. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
让
setTimeout()
来计算字符串是不好的做法。相反,请使用匿名函数:请注意,我已将所有
fadeIn()
放入一个setTimeout()
中;它执行相同的操作,因为所有超时都会同时触发(300 毫秒)。如果你的ID是字符串,你也可以这样做:虽然有点乱,但是
$.add( )
可能会成功。It's bad practice to get
setTimeout()
to evaluate a string. Instead, use an anonymous function:Note that I've put all your
fadeIn()
s into onesetTimeout()
; it does the same thing as all your timeouts will trigger at the same time (300ms). If you IDs are strings, you could do this too:Although it's a little messy, but
$.add()
might do the trick.setTimeout 接受函数回调和超时。通过将函数调用括在引号中,您将向其传递一个字符串。试试这个:
编辑:
正如 @nnnnnn 指出的,可以传递字符串,但这是一个坏想法 。本质上,当您传入一个字符串时,它会以调用者的权限进行调用,因此将无法访问“doSomething”中的范围变量,而是访问完全不同的范围。
setTimeout accepts a function callback and a timeout. By wrapping your function call in quotes, you're passing it a string. Try this:
EDIT:
As @nnnnnn pointed out, a string can be passed but it is a bad idea. Essentially, when you pass in a string it is called with the privileges of the caller and thus will not have access to the scope variables within "doSomething" but a completely different scope.