jQuery切换div并更改按钮文本

3

我有一个可以切换我的div的工作脚本,它运行得很好,但我不知道如何在单击时更改按钮文本。当显示spread div时,我需要按钮文本为“隐藏Spreads”,当未显示spread div时,按钮文本为“显示Spreads”。

脚本:

$(document).ready(function(){
  $(".spread").show();
  $(".show_hide").show();
  $('.show_hide').click(function(){
    $(".spread").toggle();
  });
});

按钮:

<input type="button" class="show_hide" value="Hide Spreads" />
2个回答

6
你可以使用 $(this).val() 来获取按钮的值并将其与其他可能的值进行比较。

$('.show_hide').click(function(){
    $(".spread").toggle();
    $(this).val( $(this).val() == 'Hide Spreads' ? 'Show Spreads' : 'Hide Spreads' );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="button" class="show_hide" value="Hide Spreads">
<div class="spread">Test</div>


太棒了,谢谢。我之前就差一点了,我漏掉了 .val()。允许时会接受作为答案。 - Mark Jones

3
您可以使用$(this).text()来获取按钮文本,并通过if else语句更改它。
<button id="show_hide">Show</button>
<div id="display"></div>
<script>
$("#show_hide").click(function(){
    $("#display").toggle();
    if($(this).text() == "Show"){
       $(this).text("Hide");
    }else{
       $(this).text("Show");
    }
});
</script>

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