点击后更改按钮文字

时间:2019-01-10 15:18:52

标签: javascript jquery

我做了一个“显示更多”按钮,它可以正常工作,但是我希望切换“显示更多”>“显示更少”>“显示更多” ...我尝试过这种方法,但是没有用。我对jquery和javascript不好。

<button type="button" id="hideshow" class="btn btn-danger btn-ver-mais">SHOW MORE </button>


jQuery(document).ready(function(){
        jQuery('#hideshow').on('click', function(event) {        
             jQuery('#btn-show-more').toggle('show');
        });
    })

$(function(){
   $("#hideshow").click(function () {
      $(this).text(function(i, text){
          return text === "SHOW MORE" , "SHOW LESS" , "SHOW MORE";
      })
   });
})

2 个答案:

答案 0 :(得分:1)

没有看到您的HTML,就很难建议您。但是,我想我对您要做的事情有所了解。

显示更多按钮的HTML外观如下:

<div id="hideshow">Show More</div>

为了更改文本,我会做这样的事情(固定)

$(function() {
    $('#hideshow').click(function() {
        if ($(this).text() === 'Show More') {
            $(this).text('Show Less');
        } else {
            $(this).text('Show More');
        }
    });
});

答案 1 :(得分:0)

按照提供的代码进行操作。该演示使用三元条件:

/* declared variable: */ 
   var txt = 
/* conditional */// 'if the text of the button is SHOW MORE'...'
   $(this).text() === 'SHOW MORE'
// '...It  is now 'SHOW LESS...'
   ? 'SHOW LESS'
// ...otherwise it is 'SHOW MORE'
   : 'SHOW MORE'

演示

$('#hideshow').on('click', function(event) {
  //  Place this INSIDE your toggle function 
  var txt = $(this).text() === 'SHOW MORE' ? 'SHOW LESS' : 'SHOW MORE';
  $(this).text(txt);
  //  Place this INSIDE your toggle function 
  $('#btn-show-more').toggle('show');
});
<article>
  <p>Chuck Norris has two speeds. Walk, and Kill.
    <button type="button" id="hideshow" class="btn btn-danger btn-ver-mais">SHOW MORE</button></p>
  <p id='btn-show-more' style='display:none'>
    Chuck Norris does not eat, he fights hunger When Chuck Norris finds fools' gold it automatically turns into real gold. Chuck Norris is nobody's fool, Chuck Norris once beat a wall at bloody knuckles. Chuck Norris drives an ice cream truck covered in human
    skulls.
  </p>
</article>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>