通过JavaScript在按钮上切换图标

时间:2014-06-12 21:03:12

标签: javascript html twitter-bootstrap

我有一个Bootstrap网页设置,显示一个可折叠的表格。每个表格行都有一个带有glyphicon-chevron-down图标的按钮。当用户点击此按钮时,该图标需要更改为glyphicon chevron-up。我尝试过几种不同的方法,但无济于事。

目前的设置是:

<script >
    function toggleChevron(button) {
        if (button.find('span').hasClass('glyphicon-chevron-down')) {
            button.find('span').className = "glyphicon glyphicon-chevron-up";
        }
        if (button.find('span').hasClass('glyphicon-chevron-up')) {
            button.find('span').className = "glyphicon glyphicon-chevron-down";
        }
    }
</script>

<button type="button" onclick="toggleChevron(this)" class="btn btn-default">
    <span class="glyphicon glyphicon-chevron-down"></span>
</button>

JSFiddle

5 个答案:

答案 0 :(得分:4)

这有效:

toggleChevron = function(button) {
  $(button).find('span').toggleClass('glyphicon-chevron-down glyphicon-chevron-up');
}

主要问题是你传递的是this,它不是jQuery对象,所以你需要将button包装在jQuery函数$(button)

http://jsfiddle.net/V9LSS/4/

答案 1 :(得分:2)

你的jsfiddle有一些错误。检查控制台。

这是我如何做到的:

http://jsfiddle.net/V9LSS/5/

var span = $('.glyphicon');

$('.btn').click(function(e){
    if(span.hasClass('glyphicon-chevron-down')) 
        span.removeClass('glyphicon-chevron-down').addClass('glyphicon-chevron-up');
    else
        span.removeClass('glyphicon-chevron-up').addClass('glyphicon-chevron-down');
});

简化一点: http://jsfiddle.net/V9LSS/7/

var span = $('.glyphicon');

$('.btn').click(function(e){
    span.toggleClass('glyphicon-chevron-down glyphicon-chevron-up');
});

答案 2 :(得分:0)

试试这个:

$('button').click(function(e) {
    var $elm = $(this).find('span'),
        cDown = 'glyphicon-chevron-down',
        cUp = 'glyphicon-chevron-up';
    if ($elm.hasClass(cDown)) {
        $elm.removeClass(cDown).addClass(cUp);
    }
    else {
        $elm.removeClass(cUp).addClass(cDown);
    }
});

http://jsfiddle.net/V9LSS/3/

或者,如果你感觉很勇敢,可以内联一切(dave的想法):

<button type="button" onclick="$(this).find('span').toggleClass('glyphicon-chevron-down glyphicon-chevron-up')" class="btn btn-default">
    <span class="glyphicon glyphicon-chevron-down"></span>
</button>

http://jsfiddle.net/V9LSS/9/

答案 3 :(得分:0)

    function toggleChevron(button) {
      if ($(button).find('span').hasClass('glyphicon-chevron-down')) {
        $(button).find('span').removeClass("glyphicon-chevron-down").addClass("glyphicon-chevron-up");
      }else{
           $(button).find('span').removeClass("glyphicon-chevron-up").addClass("glyphicon-chevron-down");
      }
    }

答案 4 :(得分:0)

您正在将dom节点作为参数传递并尝试在其上使用jquery函数,您需要在onclick中传递一个jquery元素($(this)而不是这个)。