[英]Why is this jQuery event triggering multiple times?
$('#MyVideo').on( 'timeupdate', function(event) { // Save object in case you want to manipulate it more without calling the DOM $this = $(this); var state = 0; if ((this.currentTime > (this.duration - 35)) && (state == 0)) { state = 1; console.log(state); }; //Reset state if (this.currentTime < (this.duration - 5)) { state = 0; } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="box1"> <video width=100% id="MyVideo" preload="auto" autoplay loop muted="muted" volume="0"> <source src="https://emmy-kane-9tej.squarespace.com/s/343731697.mp4" type="video/mp4"> </video> </div>
我有一个循环播放的视频,我想在视频结尾处调用一个fadeOut函数。 但是,我的函数被调用了很多次,并且似乎忽略了状态变量已更改的情况。 我对jQuery很陌生,所以我可能在这里遗漏了一些非常明显的东西,有人看到为什么这段代码会不断向控制台发送“ 1”吗?
问题是您要在函数内部设置状态,然后在每次运行该函数时将其重置。
相反,您应该做的是在.on()函数外部进行设置,然后仅在满足条件时再进行设置。
var state = 0; $('#MyVideo').on( 'timeupdate', function() { // Save object in case you want to manipulate it more without calling the DOM if ((this.currentTime > (this.duration - 35)) && (state == 0)) { state = 1; console.log(state); }; });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="box1"> <video width=100% id="MyVideo" preload="auto" autoplay loop muted="muted" volume="0"> <source src="https://emmy-kane-9tej.squarespace.com/s/343731697.mp4" type="video/mp4"> </video> </div>
看看这个jsfiddle: https ://jsfiddle.net/p98wwe5L/1/
尝试这个
var state = 0; $('#MyVideo').on( 'timeupdate', function() { // Save object in case you want to manipulate it more without calling the DOM if ((this.currentTime > (this.duration - 35)) && (state == 0)) { state = 1; console.log(state); }; });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="box1"> <video width=100% id="MyVideo" preload="auto" autoplay loop muted="muted" volume="0"> <source src="https://emmy-kane-9tej.squarespace.com/s/343731697.mp4" type="video/mp4"> </video> </div>
var state = 0; $('#MyVideo').on('timeupdate', function(event) { if (state == 1 && this.currentTime < this.duration - 5) { state = 0; console.log(state); } else if (state == 0 && this.currentTime > this.duration - 5) { state = 1; console.log(state); // Fade out } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <video width=100% id="MyVideo" preload="auto" autoplay loop muted="muted" volume="0"> <source src="https://emmy-kane-9tej.squarespace.com/s/343731697.mp4" type="video/mp4"> </video>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.