简体   繁体   English

在jQuery中切换按钮文本

[英]Toggling button text in jquery

I have an HTML button created and I want to toggle the text that is displayed in the button between two text using Javascript/JQuery. 我创建了一个HTML按钮,并且想使用Javascript / JQuery在两个文本之间切换按钮中显示的文本。 How do I do this? 我该怎么做呢?

Currently, I have: 目前,我有:

<button onclick="showAll();" class="collapse-classes">
    <span class="button-text">Show</span>
</button>

The button starts off by displaying "Show" and then switch to "Hide" when clicked and then switch to "Show" when clicked again and onward. 该按钮通过显示“显示”开始,然后在单击时切换到“隐藏”,然后在再次单击时向前切换到“显示”。 I tried changing the value of the tag but it doesn't change the text displayed. 我尝试更改标签的值,但它不会更改显示的文本。 Can anyone help with the script? 有人可以帮忙吗? thanks 谢谢

Don't use onclick . 不要使用onclick Just bind an event handler. 只需绑定一个事件处理程序即可。

Here's something you can work with: 您可以使用以下方法:

$('.collapse-classes').click(function() {
    var $this = $(this);

    $this.toggleClass('show');

    if ($this.hasClass('show')) {
        $this.text('Show');
    } else {
        $this.text('Hide');
    }
});

Following your DOM tree 遵循您的DOM树

$('.collapse-classes').click(function() {

    var span = $(this).find('span');

    if(span.text() == "Show"){
        span.text("Hide");
    } else {
        span.text("Show");
    }

});

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

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