取消选中复选框时声音未静音



我正在创建一个游戏,当开始屏幕出现时,一些音乐开始播放。现在,我还在开始屏幕中添加了一个复选框。选中此复选框时,应听到音乐。如果未选中,则不应播放任何音乐。

我有以下代码:

// Show the start screen and play some music.
game.start(game.DEMO_MODE);
if (document.getElementById('music').checked){ //check if checkbox is checked
    music.play();
    music.loop(); //Loop the music
}

如果选中复选框,此代码将在游戏加载时进行检查,如果选中,则播放音乐。这个al工作得很好,但只有当游戏加载时。如果选中了复选框,而有人在开始屏幕中取消选中复选框,则音乐将继续播放。除非他重新加载游戏,否则声音会被静音。

显然我不想这样。取消选中复选框时应停止声音,反之亦然。

我认为使用jQuery的.bind('change',function(){可以解决这个问题,但我没有成功。我希望这里有人知道需要添加什么。。。

复选框的代码(它还将其已检查/未检查状态存储到cookie或本地存储中):

jQuery(function($) {
    // Aa key must is used for the cookie/storage
    var storedData = getStorage('com_test_checkboxes_'); 
    $('div#musiccheck input:checkbox').bind('change',function(){
        // do something here tho mute or unmute the sound??
        // save the data on change
        storedData.set(this.id, $(this).is(':checked')?'checked':'not');
    }).each(function() {
        // on load, set the value to what we read from storage:
        var val = storedData.get(this.id);
        if (val == 'checked') $(this).attr('checked', 'checked');
        if (val == 'not') $(this).removeAttr('checked');
        if (val) $(this).trigger('change');
    }); 
});

如何解决此问题?

问候,

Maurice

$("#music").on('change', function() {
    if (this.checked) {
        music.play();
        music.loop();
    }else{
        music.stop();
    }
});

最新更新