4

我正在Bootstrap 3使用Jquery. 我有一个按钮,其中包含跨度标记中的图标。(使用引导程序的 glypicon)

<button id="swapArchived" class="btn btn-default btn-sm showArchived">
       <span class="glyphicon glyphicon-road"></span> Show Archived
</button>

我想在单击时更改图标和文本。除了,还有什么更好的办法

$('#swapArchived').on('click', function () {
    var $el = $(this);
    if($el.hasClass('showArchived'))
    {
      $el.html('<span class="glyphicon glyphicon-fire"></span> Show Incomplete');
    }
    else
    {      
      $el.html('<span class="glyphicon glyphicon-road"></span> Show Archived');
    }
      $el.toggleClass('showArchived');
  });

我很好奇我是否可以同时切换按钮文本和跨度类。尽量避免每次点击都写跨度。

谢谢-

4

3 回答 3

14

尝试

jQuery(function ($) {

    $('#swapArchived').on('click', function () {
        var $el = $(this),
            textNode = this.lastChild;
        $el.find('span').toggleClass('glyphicon-fire glyphicon-road');
        textNode.nodeValue = 'Show ' + ($el.hasClass('showArchieved') ? 'Incomplete' : 'Archived')
        $el.toggleClass('showArchieved');
    });
});

演示:小提琴

于 2013-11-11T04:08:27.603 回答
0

我首先将文本包装在可识别的内容中,例如

<button id="swapArchived" class="btn btn-default btn-sm showArchived">
    <span class="glyphicon glyphicon-road"></span>
    <span class="text">Show Archived</span>
</button>

然后只需更改所需的属性/文本

$('#swapArchived').on('click', function(e) {
    var btn = $(this),
        icon = btn.find('.glyphicon'),
        text = btn.find('.text'),
        toggleClass = 'showArchived';

    if (btn.hasClass(toggleClass)) {
        icon.removeClass('glyphicon-road').addClass('glyphicon-fire');
        text.text('Show Incomplete');
    } else {
        icon.removeClass('glyphicon-fire').addClass('glyphicon-road');
        text.text('Show Archived');
    }
    btn.toggleClass(toggleClass);
});
于 2013-11-11T04:07:45.980 回答
0

首先将文本放入另一个元素中,以便更容易替换:

<button id="swapArchived" class="btn btn-default btn-sm showArchived">
    <span class="glyphicon glyphicon-road"></span>
    <span>Show Archived</span>
</button>

然后,这样的事情应该可以工作:

$('#footer-top').click(function(){
    var el   = $(this),
        next = el.next(),
        txt  = "Show Incomplete";

    if (/Inc/.test(next.text()))
        var txt = "Show Archived";

    $(this).toggleClass("glyphicon-road")
           .toggleClass("glyphicon-fire");
    next.text(txt);
})

或者,更短但可能不太可读:

$('#swapArchived').click(function(){
    $(this).toggleClass("glyphicon-road")
           .toggleClass("glyphicon-fire")
           .next().text("Show " + 
               /Inc/.test( $(this).text()) ? "Archived" : "Incomplete");
}

它不是非常简洁,但也不错。

于 2013-11-11T04:38:27.100 回答