Javascript函数触发两次

时间:2017-03-07 12:51:04

标签: javascript jquery

我目前有一个javascript应用程序可播放几个视频,并根据每个问题的等待时间提出一系列问题。 但是,在触发新视频后(第2个视频),我的代码会跳过第一个问题,但我无法找到原因。有任何想法吗?谢谢。

Settings.js     var settings = {         ' appname':' ExperimentX',         ' masterpassword':' xxxx'     };

var videos = [
    {
      'video': 'movie 1.mp4',
      'questions': [
            {
                'text': `
                    blabla
                `,
                'wait': 2 * 60 + 51
            },
            {
                'text': 'How sad are you right now',
                'wait': 1 * 60 + 57
            },
            {
                'text': '',
                'wait': 57
            }
        ]
    },
    {
        'video': 'movie 2.mp4',
        'questions': [
            {
                'text': 'How happy are you right now',
                'wait': 2
            },
            {
                'text': 'How sad are you right now',
                'wait': 5
            }
        ]
    }
}

真正的JS代码:     // - 基本设置     identifier = new Date()。getTime();     videos_path ='视频/';

// -- create elements
var player = videojs('video');
var slider = $('#ex1');

// -- variables
var debug = true;
var timer = null;
var questions = [];
var currquestion = 0;
var currvideo = 0;

function log(msg){
    if (debug)
        console.log(msg);
}

function checkForLocalStorage(){
    var result = false;
    try {
        result = (typeof window.localStorage == 'undefined');
    } catch (err){
        result = false;
    }
    return result;
}

function save(key, value){
    log('Saving ' + key + ' -> ' + value);

    var sessionObject = localStorage.getItem( identifier );

    sessionObject = (null == sessionObject) ? {} : JSON.parse(sessionObject);

    sessionObject[key] = value;
    localStorage.setItem(identifier, JSON.stringify(sessionObject));
}

function toDate(ms){
    var d = new Date(0);
    d.setUTCSeconds(ms / 1000);
    return d.toLocaleString();
}

function loadAll(){
    var result = [];

    log('Loading from localstorage:');

    for (var i = 0; i < localStorage.length; i++){
        var key = localStorage.key(i);
        var obj = JSON.parse( localStorage.getItem(key) );
        obj['timestamp'] = toDate(key);

        log(obj);
        result.push( obj );
    }

    return result;
}

function refreshVideoCount(){
    log('Refreshing video counter');

    $('#currvideoCounter').text( currvideo +1 );
    $('#totalvideoCounter').text( videos.length );
}

function showEnd(){
    log('Showing end page');

    $('#ending').removeClass('hidden');
    $('#videoPlayer').addClass('hidden');

    $('#menuEnd').addClass('active');
    $('#menuVideos').removeClass('active');
}

function showQuestion(){
    console.log('Showing question, currquestion ' + currquestion + ' currvideo ' + currvideo);
    clearTimeout(timer);

    $('#modalTitle').html( questions[currquestion]['text'] ); 
    $('#modalQuestion').modal('show');

    $('#btnModal').on('click', function(){
        log('btnModal clicked, saving answer');

        save('V' + currvideo + '  Q' + currquestion, slider.slider('getValue'));

        log('Refreshing slider');
        slider.slider('refresh');

        var next = (currquestion >= questions.length-1);
        if (next == true){
            log('currquestion is the last one, cycling to next video');
            currvideo = currvideo +1;
            currquestion = 0;
            cycleVideos();
        } else {
            log('cycling to next question of this video');
            currquestion = currquestion +1;
            cycleQuestions();
        }
    });
}

function cycleQuestions(){
    log('Resuming video');

    var questionText = questions[currquestion]['text'];
    var questionWait = questions[currquestion]['wait'];

    player.play();

    if (timer){
        log('Clearing timer (cycleQuestions)');
        clearTimeout(timer);
        timer = null;
    }

    log('Setting new timer');
    timer = setTimeout(function(){
        log('Timer triggered, pausing player and showing question');
        player.pause();
        showQuestion();
    }, questionWait * 1000);
}

function cycleVideos(){
    log('Cycling to next video');

    if (timer){
        log('Clearing timer (cycleVideos)');
        clearTimeout(timer);
        timer = null;
    }

    if (currvideo > videos.length -1){
        log('Video is the last one, showing end page');
        player.pause();
        player.exitFullscreen();
        return showEnd();
    }

    log('Setting videofile and question variable');
    videoFile = videos_path + videos[currvideo]['video'];
    questions = videos[currvideo]['questions'];

    refreshVideoCount();

    log('Playing player');
    player.src({ 'src' : videoFile });
    player.play();

    cycleQuestions();
}

function showOverview(){
    log('Showing management page');

    $('#intro').addClass('hidden');
    $('#overview').removeClass('hidden');

    var items = loadAll();
    var content = '';

    log('Generating table');
    var table =
        $('<table>')
        .addClass('table')
        .append('<thead><tr>');

    for (var prop in items[0])
        table.append('<th>' + prop + '</th>');

    table
        .append('</tr></thead>')
        .append('<tbody>');

    items.forEach(function(object){
        // for every entry
        var row = '<tr>';

        for (var property in items[0]) {
            if (object.hasOwnProperty(property)) {
                // for every property
                row = row.concat(
                '<td>' + object[property] + '</td>'
                );
            }
        }
        row.concat('</tr>');
        table.append(row);
    });

    table.append('</table>');

    $('#overviewText').html(table);

    $('#btnClear').on('click', function(){
        log('Clearing storage');
        if ( confirm('Do you really want to clear all results?') ){
            localStorage.clear();
            location.reload();
        }
    });
}

function showIntro(){
    log('Showing intro page');

    $('#menuIntro').addClass('active');
    refreshVideoCount();

    $('#intro').removeClass('hidden');

    $('#introInput').keyup(function(event){
        if(event.keyCode == 13)
            $("#introBtn").click();
    });

    $('#introBtn').on('click', function(){
        var name = $('#introInput').val();
        var age = $('#introAge').val();
        var gender = $('#introGender').val();

        if (name.trim().length == 0)
            return alert('You need to fill in your name.');

        if (age.trim().length == 0)
            return alert('You need to fill in your age.');

        if (name === settings['masterpassword'])
            return showOverview();

        save('name', name);
        save('age', age);
        save('gender', gender);

        $('#intro').addClass('hidden');
        $('#videoPlayer').removeClass('hidden');

        $('#menuIntro').removeClass('active');
        $('#menuVideos').addClass('active');

        slider.slider({});
        player.requestFullscreen();
        cycleVideos();
    });

}

function disableRefresh(){
    log('Disabling F5');

    $(document).on("keydown", function(e){
        if ((e.which || e.keyCode) == 116)
            e.preventDefault();
    });
}

// setup base stuff
checkForLocalStorage();
$('#logo').text( settings['appname'] );
$('#title').text( settings['appname'] );
disableRefresh();

// show intro page
showIntro( identifier );

0 个答案:

没有答案