我们想知道是否可以有一个使用 jQuery 的函数来检查多个元素,并根据通过单击分配给它们的类型来执行其他函数。基本上,这是一个将永远运行的函数,而用户不会刷新页面。
这个想法不是依赖事件点击来执行功能,而是依赖分配给特定元素的类。
例如:
$("td.gantt").each(function() {
if($(this).hasClass("oper")) {
//execute a serie of functions
}
if($(this).hasClass("preop")) {
//execute a serie of functions
}
});
上面是执行一次,我们需要一直运行。
// define a function...
function ganttEach() {
$("td.gantt").each(function() {
// ...
});
}
// ...repeat it once every second
window.setInterval(ganttEach, 1000);
你不能“让它一直运行”(比如,在一个while(true)
循环),因为 JavaScript 是单线程的,阻塞线程意味着你的other代码永远不会运行。setInterval()
确保有必要的“间隙”供其他代码执行。
setInterval()
返回一个 ID,您可以将其存储在变量中并提供给clearInterval()
在某个时刻让它再次停止。
如果您想确保函数的每个新迭代仅开始after上一篇已经真正完成了,使用setTimeout()
反而:
// define a self-repeating function...
function ganttEach() {
$("td.gantt").each(function() {
// ...
});
window.setTimeout(ganttEach, 1000); // calls itself again in one second
}
// ...initiate self-repeating function
ganttEach();
您可能还应该包括一些方法来阻止这里无休止的重复,例如引入一个在setTimeout()
call.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)