【问题标题】:jquery toggle button valuejquery切换按钮值
【发布时间】:2011-04-18 11:06:43
【问题描述】:

在下面的代码中,当单击播放按钮时,其值应更改为暂停,当单击暂停时,应调用其他函数。如何使用 jquery 切换来做到这一点

  <input type="button" onclick ="play" value="play"/>
   <script>
     function play()
     {
               play_int();
           //   Button value to be changed to pause
     }   

  And when pause play_pause();

【问题讨论】:

  • 你到现在都试过什么???
  • 不要使用内联事件处理程序。使用 jQuery 也没有什么意义。

标签: jquery


【解决方案1】:

给你的按钮一个 ID:

<input type="button" id="play" value="play"/>

然后你可以这样做:

$('#play').click(function() {
   if ($(this).val() == "play") {
      $(this).val("pause");
      play_int();
   }
   else {
      $(this).val("play");
     play_pause();
   }
});

或者像这样稍微整洁的版本:

$(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
}

Working demo

【讨论】:

    【解决方案2】:

    尝试(在 jQuery 1.9 中)

    $("input[type='button']").toggle(
        function(){
            $(this).val("Pause");
        }, 
        function(){
            $(this).val("Play");
        }
    );
    

    DEMO

    注意:toggle 事件在 1.8 中已弃用并在 1.9 中删除

    【讨论】:

    • 这是否适用于初始值?我的意思是如果按钮已经设置为暂停,它会切换到播放吗?我不确定。
    • @diEcho 在 jQuery 1.9 及更高版本中不起作用。有没有其他方法可以做到这一点?
    • @LakshmanaKumar 切换事件在 1.8 中已弃用,并在 1.9 中删除:forum.jquery.com/topic/…
    【解决方案3】:
    $('#play_button_id').toggle(play,play_pause);
    

    这会在你第一次点击按钮时触发 play() 函数

    以及第二次点击按钮时的 play_pause()

    【讨论】:

    • 不,不会。除非这些函数返回另一个函数:)。你应该使用toggle(play, play_pause)
    【解决方案4】:

    我会说

    statuses = ['Play', 'Pause'];
    $('#btn_play').val(
        $('#btn_play').val() == statuses[0]
        ? statuses[1] : statuses[0]
    );
    

    【讨论】:

      【解决方案5】:

      一个最简单的想法可以是这个

      function play(action) {
       { 
         if(action=='play') { 
            play_int(); 
            $("#btn_play").val('pause');
         }
         else { 
            pause_int(); 
            $("#btn_play").val('play');
         }
      }
      
      $("#btn_play").click(function() {
         val = $(this).val();
         play(val);
      }
      

      【讨论】:

        猜你喜欢
        • 2013-05-26
        • 1970-01-01
        • 2020-05-20
        • 1970-01-01
        • 2013-05-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-22
        相关资源
        最近更新 更多