[英]Unable to bind events in JQuery?
為什么我的簡單 JQuery 代碼中沒有綁定事件? - http://pastebin.com/24J6q5G0
相關欄目:
<div class="videoWrapper">
<video controls preload autoplay>
<source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4">
<source src="http://techslides.com/demos/sample-videos/small.ogv" type="video/ogg">
</video>
</div>
<div class="videoWrapper">
<video controls preload="none">
<source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4">
<source src="http://techslides.com/demos/sample-videos/small.ogv" type="video/ogg">
</video>
</div>
和 javascript:
$(document).ready(function() {
var vid0 = $(document.getElementsByClassName('videoWrapper')[0]);
var vid1 = $(document.getElementsByClassName('videoWrapper')[1]);
vid1.hide();
vid0.bind('ended', function() {
vid1.show();
})
})
(我一直在關注HTML5 視頻結束時的檢測)
結束的事件沒有傳播(冒泡),所以嘗試
$(document).ready(function() {
var wrappers = $('.videoWrapper');
wrappers.eq(1).hide()
wrappers.eq(0).find('video').bind('ended', function() {
wrappers.eq(1).show();
})
})
在您的情況下,您將事件綁定到包裝div
元素,但ended
事件不會冒泡到父元素,這意味着您的處理程序永遠不會被執行。
首先,HTML5 視頻的事件在video
元素上觸發,因此您附加到了錯誤的元素。 此外,您創建 jQuery 選擇器的方法有點奇怪。 試試這個:
var $vid0 = $('.videoWrapper video').eq(0);
var $vid1 = $('.videoWrapper video').eq(1);
$vid1.parent().hide();
$vid0.bind('ended', function() {
$vid1.parent().show();
})
它不起作用的原因是因為您的 vid0 是包裝器 div,而ended
事件需要video
標簽。
這是一個有效的演示修復: http : //jsfiddle.net/
我在video
標簽中添加了#video0
和#video1
。
我使用的解決方案(認為當時只有一個 [錯誤] 答案)是:
$(document).ready(function() {
var vid0 = $(document.getElementsByClassName('videoWrapper')[0]);
var vid1 = $(document.getElementsByClassName('videoWrapper')[1]);
vid1.hide();
vid0.children().bind('ended', function() { // Note this line
vid1.show();
})
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.