我使用的是Bootstrap list-group
,列表项有两个类。我正在使用JavaScript,当我只有一个类video
时,它工作正常,但是当我添加list-group-item
类时它不起作用。
<html>
<head></head>
<body>
<div class="list-group list-special">
<a class="video list-group-item active" href="M0mx8S05v60"><span class="badge">8:56</span>Lec 1: What is Signal?</a>
<a class="video list-group-item" href="F5h3z8p9dPg"><span class="badge">9:35</span>Lec 2: What is an Analog Signal?</a>
<a class="video list-group-item" href="jRL9ag3riJY"><span class="badge">8:48</span>Lec 3: What is Digital Signal?</a>
<a class="video list-group-item" href="izBaDRyqnBk"><span class="badge">5:13</span>Lec 4: Need of Digital Signal</a>
<a class="video list-group-item " href="2xXErGeeb_Q"><span class="badge">6:42</span>Lec 5: Inroduction to Digital Electronics</a>
<a class="video list-group-item" href="RF9I6UzI4Rc"><span class="badge">9:41</span>Lec 6: Switch and Bits Intuition</a>
</div>
<script type="text/javascript">
var onVideoLinkClick = function(e){
if( e.target.tagName == 'A' && e.target.classList.contains('video')) {
var videoID = e.target.getAttribute('href');
history.pushState(
{videoID: videoID},
e.target.innerText,
'video-'+videoID)
changeVideo(videoID)
e.preventDefault();
}
}
var changeVideo = function(videoID){
var src = 'https://www.youtube.com/embed/'+videoID;
document.getElementById("videoFrame").src = src;
}
var onUrlChange = function(e){
changeVideo(e.state.videoID)
}
window.addEventListener('click', onVideoLinkClick);
window.onpopstate = onUrlChange;
</script>
</body>
</html>
答案 0 :(得分:0)
我测试了您的代码,看起来很好,但是当您点击<span class="badge">
代码时它不会通过,因为它不会通过条件e.target.tagName == 'A'
解决方案是仅将事件监听器添加到video
元素而不是window
,我使这个工作小提琴https://jsfiddle.net/prh6vfza/
我还建议您使用jquery附加事件
答案 1 :(得分:0)
为什么要这么复杂!您可以直接获取带有视频类的锚标签,并将事件监听器附加到它。通过这种方式,您可以避免检查目标是否为a
的条件
JS
// Get all anchor tags with video class
var allAnchorTags = document.getElementsByClassName('video');
// Use [].slice.apply(cards) to convert the cards NodeList into an array
// Iterate over the cards array with a .forEach
[].slice.apply(allAnchorTags).forEach(function(aTags,index){
// Attach eventlistener to it
aTags.addEventListener('click',function(e){
changeVideo(e.target.getAttribute('href'));
},false)
})
function changeVideo(videoId){
alert(videoId)
var src = 'https://www.youtube.com/embed/'+videoID;
document.getElementById("videoFrame").src = src;
}
注意:无法理解这一部分。所以没有包含在演示中。似乎它是一个数组,并希望将元素推入其中。请注意所有关闭支架
history.pushState(
{videoID: videoID},
e.target.innerText,
'video-'+videoID)
changeVideo(videoID)
e.preventDefault();
}