简体   繁体   English

如何切换按钮的onclick =“ function”

[英]How can I toggle a onclick=“function” for a button

I have a button that plays and stops a video. 我有一个播放和停止视频的按钮。 How can I toggle between the .play() and .pause() efficiently? 如何有效地在.play()和.pause()之间切换?

<button id="thebutton" onclick="BV.getPlayer().play();"></button>

First off, I would suggest not using inline event handlers. 首先,我建议不要使用内联事件处理程序。 If you're using jQuery, then I suggest you use that. 如果您使用的是jQuery,那么我建议您使用它。

After each click, set a variable to tell whether it's playing or not, then trigger the correct action. 每次单击后,设置一个变量以告知其是否正在播放,然后触发正确的操作。

$(function(){
    $('#thebutton').click(function(){
        var isPlaying = $(this).data('isplaying');

        if(isPlaying){
            BV.getPlayer().pause();
        }
        else{
            BV.getPlayer().play();
        }

        $(this).data('isplaying', !isPlaying);
    });
});

jQuery used to have a .toggle() "event" , but it was removed. jQuery曾经有一个.toggle() “事件” ,但已被删除。

Add a class that acts as check for the player status. 添加一个类来检查玩家状态。 And then use this code. 然后使用此代码。

$("#theButton").click(function() {
    if($(this).hasClass('playing')) {
        BV.getPlayer().pause();   
    } else {
        BV.getPlayer().play();
    }
    $(this).toggleClass('playing')
})
$('#thebutton').click(function() {

if ($(this).val() == "play") {
  $(this).val("pause");
  play_int();
}

else {
  $(this).val("play");
 play_pause();
 }         
});

or 要么

 $(function(){
$('#play').click(function() {
   // if the play button value is 'play', call the play function
   // otherwise call the pause function
   $(this).val() == "play" ? play_int() : play_pause();
});
});

function play_int() {
$('#play').val("pause");
// do play
}

function play_pause() {
$('#play').val("play");
// do pause
}

aka jquery toggle button value aka jQuery切换按钮值

var isPlaying = false;
var player = BV.getPlayer();
$("#thebutton").click(function() {
    if (isPlaying) {
        player.pause();
        isPlaying = false;
    } else {
        player.play();
        isPlaying = true;
    }
});

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

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