简体   繁体   English

使用jQuery和JavaScript在按钮上添加开关行为

[英]Adding on-off behavior on a button with jquery and javascript

I'm really stuck with this. 我真的很坚持。 The logic here is to have one script that works with different audio elements on the page and makes switch between PLAY and PAUSE buttons by adding/removing classes. 这里的逻辑是使一个脚本可以与页面上的不同音频元素一起使用,并通过添加/删除类在PLAY和PAUSE按钮之间进行切换。 Any idea what to change/add in order to make it work. 任何想法为了使它起作用而需要更改/添加的内容。 Anything will be appriciated! 一切都会被应用!

<audio id="arbeiten" preload="none">
    <source src="../../../audio/sound1.mp3" type="audio/mpeg">Your browser does not support the audio element.
</audio>

<button id="play-button" class="btn btn-xs" data-action="play" data-target="#arbeiten">
       Play
</button>
<button id="pause-button" class="btn btn-xs hide" data-action="pause" data-target="#arbeiten">
    Pause
</button>

<script>
     $('body').on('click','[data-action]',function() {
         var action = $(this).data('action');
         var target = $(this).data('target');
         switch(action) {
             case 'play':
                 $(target)[0].play();
                 $(target).addClass("hide");
                 $(this).removeClass('hide');
                 break;
             case 'pause':
                 $(target)[0].pause();
                 $('#pause-button').addClass("hide");
                 $('#play-button').removeClass('hide');
                 break;
         }
         console.log('Called action ',action,' on element ',target);
     });

</script>

Have you tried $('#pause-button').hide(); 您是否尝试过$('#pause-button')。hide(); $('#play-button').show(); $('#play-button')。show();

It doesn't use classes but it seems to solve the problem of hiding and showing buttons. 它不使用类,但似乎解决了隐藏和显示按钮的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM