开发者

Improving the JQuery MP3 Player Plugin code

开发者 https://www.devze.com 2022-12-20 03:58 出处:网络
I am not the most experienced jquery auth开发者_如何学Pythonor and I came up with a solution to a simple problem, but to me it doesn\'t seem like the best way to do it. I think the code explains it be

I am not the most experienced jquery auth开发者_如何学Pythonor and I came up with a solution to a simple problem, but to me it doesn't seem like the best way to do it. I think the code explains it best:

$("#play_button").click( function () {
    $("#play_button").hide();
    $("#pause_button").show();
});

$("#pause_button").click( function () {
    $("#play_button").show();
    $("#pause_button").hide();
});

Any suggestions on a better block of code to accomplish the same thing?


Assuming one starts visible, and the other doesn't:

$("#pause_button, #play_button").click(function(){
  $("#play_button, #pause_button").toggle();
});

Online demo: http://jsbin.com/ewave/edit

If you apply a simple class to both: class='button', you can make it even simpler:

$(".button").click(function(){
  $(".button").toggle();
});


Building on Jonathan's answer, I kinda like this, but it's less explicit:

var buttons = $('#play_button, #pause_button');
buttons.click($.proxy(buttons, 'toggle'));

It does, though, offer the advantage of not having to repeat yourself when it comes to naming the buttons.


Your code looks fine, but I would at least do this:

$("#play_button").click( function () {
    $(this).hide();
    $("#pause_button").show();
});

$("#pause_button").click( function () {
    $(this).hide();
    $("#play_button").show();
});

Using $(this) adds clarity, IMHO.

Johnathan Sampson's solution is also good, if you prefer that.


Similar to Jonathan's answer except i would use a catchall id an then change the class...

pseudo html

<element id="player_button" class="play">
</element>

css:

#player_button { /* general style rules like position dimensions cursor */}
#player_button.play {/* play button bg image */}
#player_button.pause {/* pause button bg image */}

js:

$('$player_button').click(function(){
   var button = $(this);
   if(button.is('.play'){
      // logic to initiate play
   }
   if(button.is('.pause')){
      // logic to initiate pause
   }

   button.toggleClass('pause').toggleClass('play');
});

Ofcourse if youre using 1.4 you can supply a function to toggleClass to detect which classes should be added/removed. This is sut preference to not have two separate elements in the DOM unless it makes functional sense.

0

精彩评论

暂无评论...
验证码 换一张
取 消