jQuery 切换按钮的值

11
在下面的代码中,当点击播放按钮时,它的值应该被改为暂停,当点击暂停时,应该调用其他函数。如何使用jQuery toggle来实现这一点。
  <input type="button" onclick ="play" value="play"/>
   <script>
     function play()
     {
               play_int();
           //   Button value to be changed to pause
     }   

  And when pause play_pause();

你到目前为止尝试了什么? - jimy
不要使用内联事件处理程序。在jQuery中,这也没有什么意义。 - kapa
5个回答

23

给你的按钮添加一个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
}

演示


14

在jQuery中尝试(版本小于1.9

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

演示

注意:自1.8版本起,toggle事件已被弃用并在1.9中移除。


1
这个会适用于初始值吗?我的意思是,如果按钮已经设置为暂停,它会切换到播放吗?我不确定。 - Pierre de LESPINAY
@diEcho 在 jQuery 1.9 及以上版本中无法工作。还有其他方法可以实现类似的功能吗? - Lakshmana Kumar
1
@LakshmanaKumar toggle事件在1.8中被弃用,在1.9中被删除 阅读:http://forum.jquery.com/topic/problem-with-toggle-function-in-jquery-1-9-1 - xkeshav

2
$('#play_button_id').toggle(play,play_pause);

第一次单击按钮将触发play()函数

第二次单击按钮将触发play_pause()函数


不会的,除非这些函数返回另一个函数 :). 你应该使用 toggle(play, play_pause) - kapa

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

1

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

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);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接