替换标签文本会删除封闭的范围

时间:2016-08-22 11:55:13

标签: jquery html twitter-bootstrap

我正在尝试在bootstrap中切换折叠面板的文本和图标。图标似乎正在改变,但如果我尝试更换标签文本,跨度将被删除,我只看到图标。这有什么问题?

HTML

    <div class="row bgGray text-center">
            <div id="divOptionsCI" class="col-xs-12 clickable" data-toggle="collapse" data-target="#containerFrequencyInflation">    
                <label id="lblMoreOptCI" class="clickable" style="height:30px;color:#FFF;">
                  <span class="glyphicon glyphicon-chevron-down glyphCollapseCI" style="top:3px;"></span> 
                   More options 
                  <span style="top:3px;" class="glyphicon glyphicon-chevron-down glyphCollapseCI"></span>
               </label>
            </div>
    </div>

JS

$('#containerFrequencyInflation').on('shown.bs.collapse', function () {                        
        $(".glyphCollapseCI").removeClass("glyphicon-chevron-down").addClass("glyphicon-chevron-up");
        $("#lblMoreOptCI").text('Fewer Options');
});
$('#containerFrequencyInflation').on('hidden.bs.collapse', function () {        
        $(".glyphCollapseCI").removeClass("glyphicon-chevron-up").addClass("glyphicon-chevron-down");
        $("#lblMoreOptCI").text('More Options');
});

2 个答案:

答案 0 :(得分:1)

因为<span>位于<label>内。您应该更改<span>元素之间的文本,而不是<label>元素之间的文本。

下面我为您的文字创建<span>,在js中,只需更改<span>的文字:

<div class="row bgGray text-center">
    <div id="divOptionsCI" class="col-xs-12 clickable" data-toggle="collapse" data-target="#containerFrequencyInflation">    
        <label id="lblMoreOptCI" class="clickable" style="height:30px;color:#FFF;"> 
            <span class="glyphicon glyphicon-chevron-down glyphCollapseCI" style="top:3px;"></span> 
            <span id="lblMoreOptCISpan">More options</span>
            <span style="top:3px;" class="glyphicon glyphicon-chevron-down glyphCollapseCI"></span>
        </label>
    </div>
</div>

$('#containerFrequencyInflation').on('shown.bs.collapse', function () {                        
   $(".glyphCollapseCI").removeClass("glyphicon-chevron-down").addClass("glyphicon-chevron-up");
   $("#lblMoreOptCISpan").text('Fewer Options');
 });

$('#containerFrequencyInflation').on('hidden.bs.collapse', function () {        
  $(".glyphCollapseCI").removeClass("glyphicon-chevron-up").addClass("glyphicon-chevron-down");
  $("#lblMoreOptCISpan").text('More Options');
});

答案 1 :(得分:0)

基本上text()函数会替换或覆盖所选元素的内容,因此请使用span内容来覆盖标签文本。

<label id="lblMoreOptCI" class="clickable" style="height:30px;color:#FFF;">
              <span class="glyphicon glyphicon-chevron-down glyphCollapseCI" style="top:3px;"></span> 
              <span class='changelabel'> More options </span>
              <span style="top:3px;" class="glyphicon glyphicon-chevron-down glyphCollapseCI"></span>
           </label>

的js

$('.changelabel').text('your response text here');