jQuery text not toggling on first click

I'm trying to toggle text of a span whenever it's parent anchor tag is clicked. Here is the HTML:

<h2 class="panel-title">
    <a href="#collapse1">
        <span class="ui-hidden-accessible">expand</span>
    </a>
</h2>

while this is the javascript of the changeText function which is called on each click of the anchor tag

function changeText() {
var taskDivClass = $('.panel-title a');
$(taskDivClass).each(
    function() {
        var $this =  $(this);
        if($this.hasClass('collapsed')) {
            var taskDivSpanText = $this.find('.ui-hidden-accessible');
            taskDivSpanText.html('expand');
        }
        else {
            var taskDivSpanText = $this.find('.ui-hidden-accessible');
            taskDivSpanText.html('collapse');
        }
    }
);
}

I'm using the each method because there are multiple such blocks in the page, and for each click event only that particular span should change.

The .collapsed class dynamically toggles on the anchor tag when user clicks on it.

The issue is when the first time user clicks on the anchor tag, the text is not toggled. On next click it does.

I'm really not sure what I'm missing here. If someone has a clue, please point it out.


If you dont want to add/remove class work with .html().

Hope this will help you..

$(document).ready(function(){
  $("a").click(function(){
    var spanClick= $(this).find('.ui-hidden-accessible');
    if (spanClick.html()==="Expand"){
     spanClick.html("Collapse");
    }
    else{
     spanClick.html("Expand");
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2 class="panel-title">
  <a href="#collapse1"   >
    <span class="ui-hidden-accessible">Expand</span>
  </a>
</h2>

您不需要循环 - 原始选择器已适用于所有匹配元素

$(function() {
  $('.panel-title a').on('click', function() {

    var $this = $(this);

    if ($this.hasClass('collapse')) {
      var taskDivSpanText = $this.find('.ui-hidden-accessible');
      $this.removeClass('collapse');
      taskDivSpanText.html('expand');

    } else {
      var taskDivSpanText = $this.find('.ui-hidden-accessible');
      taskDivSpanText.html('collapse');
      $this.addClass('collapse');
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2 class="panel-title">
    <a href="#collapse1" class="collapse">
        <span class="ui-hidden-accessible">collapse</span>
    </a>
</h2>
<h2 class="panel-title">
    <a href="#collapse2">
        <span class="ui-hidden-accessible">expand</span>
    </a>
</h2>
<h2 class="panel-title">
    <a href="#collapse3">
        <span class="ui-hidden-accessible">expand</span>
    </a>
</h2>
链接地址: http://www.djcxy.com/p/83974.html

上一篇: 在点击时切换图像的父容器

下一篇: jQuery文本不会在第一次点击时切换