Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
385 views
in Technique[技术] by (71.8m points)

javascript - Toggle Bootstrap button text on button click?

I want to toggle the text on a button each time it's clicked, e.g. from "Show more..." to "Show less...".

I have a button that's used to expand or collapse a nearby block (see the Collapse section of the Bootstrap docs, click the example "Link with href" button there to see what I mean).

The HTML for such a Bootstrap button looks like this:

<a class="btn btn-primary" data-toggle="collapse" href="#collapseExample">
    See more...
</a>

When the related block is collapsed I want the button text to be e.g. "Show more..." and when it's expanded I want it to be e.g. "Show less...".

I've seen solutions that separate the button text off into jQuery, Javascript or CSS - but that makes it difficult to read the HTML (the button text is somewhere else entirely to the button) and also makes it more difficult to localize.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I tried a couple of these approaches before cobbling this one together. It is the simplest, most readable approach I've seen so far:

    <a href="#" data-toggle='collapse' 
        data-target="#filters,#view_filters,#hide_filters">
      <span id='view_filters' class='collapse in'>View Filters</span>
      <span id='hide_filters' class='collapse out'>Hide Filters</span>
    </a>

    <div id="filters" class="collapse out">
      Now you see me!
    </div>

The main purpose of this link is to toggle visibility of div#filters...but it takes advantage of multiple selectors in data_target to also toggle the visibility of the two versions of the link text. Just make sure you've got one text as ".collapse .in" and the other as ".collapse .out".

Beyond its simplicity, I like that this is very reliable. Because the tag is never hidden or manipulated, you'll never accidentally lose the view/hide link while debugging.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...