JQuery - 每 2 秒单击一次按钮
基本上我有一个刷新按钮,当用户单击刷新按钮时,它会调用 Web 服务,获取数据并刷新 div 容器以显示新数据。
但我想更新 div 容器而不让用户单击刷新按钮......
我如何让 jQuery 每 2 秒单击我的按钮,而不刷新整个页面?或者有更好的方法来做到这一点吗?
Basically I have a refresh button, when the user clicks the refresh button it calls a web service, gets the data back and refreshes a div container to display the new data.
But I want to update the div container without having the user click the refresh button....
How do I have jQuery click my button every 2 seconds, without refreshing the entire page? or is there a better way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 setInterval 在每个给定时间段后调用一个函数:
这将每 2 秒调用一次 myBtn 元素上的单击事件。
请注意,如果您发送 ajax 请求,有时可能需要比您的时间间隔更多的时间来接收响应。这可能会导致一些问题。因此请考虑使用递归调用。(从 ajax 回调函数调用 click 函数)
you can use setInterval to call a function after every given period of time:
this will invoke a click event on myBtn element in every 2 seconds.
Be careful, if you're sending an ajax request, it may sometimes need more time to receive a response, than your interval. this may cause some problems. so consider using recursive calls instead. (invoke click function from an ajax callback function)
您可以使用
setInterval
每两秒运行一个函数:然后让被调用的函数调用按钮的单击处理程序。理想情况下,您可以直接调用点击处理程序,而不必使用
$x.click()
。使用
setTimeout
可能是一个更好的主意:然后回调函数将调用点击处理程序,当该处理完成时,它将再次调用
setTimeout
来触发自身。这种方法将防止您的定时事件相互超出。由于所有代码都是您的,您可以重组它,以便$.ajax
成功和错误回调(或者可能是complete
回调)可以重新启动计时器。You could use
setInterval
to run a function every two seconds:And then have the called function call the button's click handler. Ideally you'd be able to call the click handler directly without have to say
$x.click()
.Using
setTimeout
might be a better idea:Then the callback function would call the click handler and, when that finishes, it would call
setTimeout
again to trigger itself. This approach will keep your timed events from overrunning each other. Since all the code is yours, you can restructure it so that the$.ajax
success and error callbacks (or perhaps thecomplete
callback) could restart the timer.您可以使用
setInterval
命令使用干净的旧 JavaScript 来完成此操作。下面是一个例子:如果你想在这里停止自动更新,你可以使用命令
clearInterval(x);
。如果刷新数据需要很长时间,可以让每次请求之间有2秒的间隔。
对于第二个示例,您可以在刷新完成后直接放置 setTimeout。
You can do this with clean old javascript using the
setInterval
command. Here is an example:If you want to stop the automatic updates here, you can use the command
clearInterval(x);
.If the refreshing of data takes a long time, you can make it so that there is 2 second interval between each request.
For the second example, you would place the setTimeout directly after the refreshing is complete.