在我的项目中,我有一个在预定时间显示视频的 channel 。当没有视频时,在显示视频的div处会显示一张ID为pgmimg
的图片。
<img id="pgmimg"/>
为了实现此功能,我调用 setInterval()
它将检查视频 div 中的当前内容。如果是默认图片,则会调用ajax函数检查此时是否有视频。如果有,则发送响应。
$(document).ready(function() {
if ($('#pgmimg').length) // checking for next video only if there is no any video playing, ie., if the default image class is present
{
setInterval(function() {
nextchannel('<?php echo base_url();?>')
}, 3000);
}
});
function nextchannel(baseurl)
{
$.ajax({
type: 'post',
datatype: 'html',
url: baseurl + 'index.php/index/nextvideo',
success: function(response)
{
$('.videoarea').html(response);
}
})
}
PHP
function nextvideo()
{
$currentpgm = $this->db->query("query for fetching current programme");
$pgm = $currentpgm->row();
$currentpgnnum = $currentpgm->num_rows();
if ($currentpgnnum > 0)
{ // if there is any program at current time then display the video
echo '<a href="' . base_url() . 'channel/' . $pgm->programme_source . '/' . $pgm->video . '" class="fplayer" id="flowplayer"></a>
<input type="hidden" name="starttime" id="starttime" value="' . $pgm->starttime . '"/>
<input type="hidden" name="currentdate" id="currentdate" value="' . $currentdate . '"/>';
}
else
{ // if there is no video, then show the default image with id pgmimg
echo '<img src="'.base_url().'images/video_sample.png" alt="video" id="pgmimg"/>';
}
exit;
}
现在的问题是,在 setInterval
函数中,它无法检查默认图像 id 是否存在(仅当网页中存在默认图像 id 时才调用 setInterval)$ ('#pgmimg').length
。视频正在播放中,
但是 setInterval() 函数再次被调用。但这不应该发生。
谁能帮我解决这个问题吗?
提前致谢。
最佳答案
使用递归 setTimeout
调用代替 setInterval
,这样您就可以在需要时停止轮询。使用 setTimeout
进行轮询的额外好处是,如果由于某种原因需要超过 3 秒才能获得响应,您就不会开始发出重叠请求。
$(document).ready(function() {
if ($('#pgmimg').length) // checking for next video only if there is no any video playing, ie., if the default image class is present
{
setTimeout(function() {
nextchannel('<?php echo base_url();?>')
}, 3000);
}
});
function nextchannel(baseurl)
{
$.ajax({
type: 'post',
datatype: 'html',
url: baseurl + 'index.php/index/nextvideo',
success: function(response)
{
$('.videoarea').html(response);
if ($('#pgmimg').length) // call again if necessary
{
setTimeout(function() {
nextchannel('<?php echo base_url();?>')
}, 3000);
}
}
})
}
关于javascript - 使用jquery检查div的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23903330/