使用JQuery更改YouTube iframe src

时间:2018-02-22 08:06:07

标签: javascript jquery iframe youtube-iframe-api

我正在构建视频播放器页面。我使用Ajax加载了与YouTube频道相关联的iframe和其他视频。我正在尝试使用iframe src事件在多个锚上更改onclick,但onclick事件似乎无法根据我的代码执行。

Ajax生成的HTML



	    
    $('.play-video').on('click',function(){
    	
    	$('#video-view iframe').attr('src', $(this).data('src'));
    	$('#video-title').text($(this).data('title'));
    	$('#video-description').text($(this).data('description'));
    	
    	$('html, body').animate({
            scrollTop: $('#video-viewer').offset().top
        }, 2000);
    });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="vid-youtube">
    	 <div class="video" id="video-viewer">
    		<iframe name="youtube_player" width="560" height="250" frameborder="0" src="//www.youtube.com/embed/8VYX4jDH63c?theme=light&amp;color=red&amp;showinfo=0" allowfullscreen="true"></iframe>
    	</div>
    	<div class="col-md-12" style="padding: 20px;">
    		<h4 id="video-title">Born Depressed(take 1) - Jimquisition Intro Theme Sax Cover</h4>
    		<p id="video-description">Born Depressed by Drill Queen with Live Sax</p>
    		<hr>
    	</div>						  					
    	
    	<div style="padding: 20px !important;">
    		<div class="row videos-list">
    			<div class="col-sm-3 col-xs-6">			
    				<div class="item active">	
    					<a href="#" style="color: #565a5c" class="play-video" data-src="//www.youtube.com/embed/8VYX4jDH63c?autoplay=1&amp;theme=light&amp;color=red&amp;showinfo=0" data-description="Born Depressed by Drill Queen with Live Sax">	                  			                  		
    						<img src="https://i.ytimg.com/vi/8VYX4jDH63c/mqdefault.jpg" >
    						Born Depressed(Take 1) 
    					</a>
    				</div>
    			</div>
    			<div class="col-sm-3 col-xs-6">			
    				<div class="item ">	
    					<a href="#" style="color: #565a5c" class="play-video" data-src="//www.youtube.com/embed/L-rAHwcCb4k?autoplay=1&amp;theme=light&amp;color=red&amp;showinfo=0" data-description="Born Depressed by Drill Queen with Live Sax, Drums" data-title="Get Lucky - Daft Punk">	                  			                  		
    						<img src="https://i.ytimg.com/vi/L-rAHwcCb4k/mqdefault.jpg">
    						Get Lucky - Daft Punk
    					</a >
    				</div>
    			</div>
    		</div>
    	</div>
    </div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

$(document).on('click', '<selector>', function() {});适用于动态创建的元素,如果使用以下语法:

$(document).on('click', '.play-video', function() { $('#video-viewer iframe').attr('src', $(this).data('src')); $('#video-title').text($(this).data('title')); $('#video-description').text($(this).data('description')); $('html, body').animate({ scrollTop: $('#video-viewer').offset().top }, 2000); });

{{1}}