使用slideToggle()更改文本无法按预期工作

时间:2017-03-01 09:13:38

标签: jquery

我希望在切换表格的可见性时更改元素内的文本。我可以切换它们,但无法更改元素内的文本。

<table class="table funds-table">
<thead class="table-head">
<tr>
  <th id="equity-text">EQUITY</th>
  <th id="eq-show-less">SHOW LESS</th>

</tr>
</thead>

<tbody id = "equity-body">
 <tr>

  <td class = "fund-name">

    <div class = "col-xs-1 padding-lr-zero checkbox-div"><input type="checkbox" id = "checkbox1">
      <label for="checkbox1"><span class="checkbox"><img src="icons/check_dis.png"></span></label></div>

    <div class = "col-xs-11 fund-name-div"><span class = "span-fund-name">HDFC DYNAMIC FUND HDFC DYNAMIC FUND HDFC DYNAMIC</span><p class = "currently-inv"> Currently invested <span class = "curr-span-amt">Rs. 50,000</span></p></div>

  </td>

  <td class = "fund-amount"><p class = "fund-amount-inner">Rs. 50,00,000</p></td>
</tr>

<tr>

  <td class = "fund-name">

    <div class = "col-xs-1 padding-lr-zero checkbox-div"><input type="checkbox" id = "checkbox2">
      <label for="checkbox2"><span class="checkbox"><img src="icons/check_dis.png"></span></label></div>

    <div class = "col-xs-11 fund-name-div"><span class = "span-fund-name">HDFC DYNAMIC FUND HDFC DYNAMIC FUND HDFC DYNAMIC</span></div>

  </td>

  <td class = "fund-amount"><p class = "fund-amount-inner">Rs. 50,00,000</p></td>
</tr>

它会在tbodyvisible时发出警报,但在hidden时则会发出警报。

  $('#eq-show-less').on('click',function(){

    $('#equity-body').slideToggle('slow');

  });


  $(function(){
    if ($('#equity-body').is(':visible')) {
      $('#eq-show-less').text("SHOW LESS");
      alert('visible');
    }

    if($('#equity-body').is(':hidden')){
      $('#eq-show-less').text("SHOW MORE");
      alert('not visible');
    }
  });

以下是fiddle

我希望在tbody可见时将文字更改为显示更少,并在隐藏tbody显示更多

1 个答案:

答案 0 :(得分:3)

问题是因为您只在页面加载时检查元素的:visible状态。

要解决此问题,您需要在fadeToggle()动画完成时进行检查。为此,您可以使用callback参数,如下所示:

$('#eq-show-less').on('click', function() {
    $('#equity-body').slideToggle('slow', function() {
        $('#eq-show-less').text($(this).is(':visible') ? 'SHOW LESS' : 'SHOW MORE');
    });
});

Updated fiddle