code fails to work outside a jsFiddle

北战南征 提交于 2019-11-28 02:29:25

Your jQuery code is running BEFORE the DOM is ready so your jQuery code doesn't find any objects in the page so they don't do anything. You should either locate it at the end of the body AFTER the DOM items are loaded or use jQuery(document).ready() to make your code wait until the DOM is ready.

Your jsFiddle is set to only run your code after the DOM is loaded so that could be why it works in jsFiddle.

Change your code to this:

<script>
$(document).ready(function() {

$('#video_1, #video_2').hide();

      $('.icon_1').click(function(){
            $('#video_2').fadeOut(function(){
            $('#video_1').fadeIn();
            });
      });

      $('.icon_2').click(function(){
            $('#video_1').fadeOut(function(){
            $('#video_2').fadeIn();
            });
        });

$('.icon_1').click(function(){

            $('.video_2').get(0).pause();
            $('.video_2').get(0).currentTime = 0;
            $('.video_1').get(0).play();
        });

$('.icon_2').click(function(){
            $('.video_1').get(0).pause();
            $('.video_1').get(0).currentTime = 0;
            $('.video_2').get(0).play();
        });
});
</script>

You probably also want to fix the location of your script tags. They should either be inside the <head> tags or inside the <body> tags. You have them neither (before <head> tags). Most browsers will likely tolerate, but not technically a good idea.

Move head just after html

So it looks like

<html>
<head>
<script...etc..
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!