Toggling button text in jquery

2019-02-26 07:19发布

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. 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

2条回答
成全新的幸福
2楼-- · 2019-02-26 07:42

Don't use 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');
    }
});
查看更多
Rolldiameter
3楼-- · 2019-02-26 08:00

Following your DOM tree

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

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

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

});
查看更多
登录 后发表回答