سؤال

I am working on a music player and i believe my prevent default is not working. When I hit play everything works fine. The button switches to the pause button and the music plays. However when I hit pause the page refreshes. Any ideas?

Thanks!

play.on('click', function (e) {
    e.preventDefault();
    song.play();
    $(play).replaceWith('<a class="button gradient" id="pause" href="" title=""></a>');
    container.addClass('containerLarge');
    cover.addClass('coverLarge');

});

pause.on('click', function (e) {
    e.preventDefault();
container.removeClass('containerLarge');
    cover.removeClass('coverLarge');
    song.pause();
    $('#pause').replaceWith('<a class="button gradient" id="play" href="" title=""></a>');

});
هل كانت مفيدة؟

المحلول

You're replacing the elements with new ones. The event handlers are bound to the old elements, not the new ones, and the references stored in variables play and pause will be the old detached DOM elements as well.

You need to leave the elements alone, and programatically hide/show them, rather than completely removing them and replacing them with the other element:

play.on('click', function (e) {
  e.preventDefault();
  play.hide();
  pause.show();
});

نصائح أخرى

$('body').on('click','#pause',function(e){
$('body').on('click','#play',function(e){

You didn't provide HTML but these should work.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top