通过jquery分配样式attr

时间:2016-09-19 11:42:50

标签: javascript jquery html

我正在尝试为这些跨度按钮指定颜色,如果我将类放在span类中,它有点工作,但有时它不会改变颜色,而且我希望能够只设置一个按钮有色。而且我还需要将值存储在样式中,因为我希望在加载页面时将其着色。

while($stmt->fetch()): ?>
<div class="statusicons">
    <a href="#" class="btn btn-xs btn-default"><span  data-color="0" class=" glyphicon glyphicon-ok" style=""></span></a>
    <a href="#" class="btn btn-xs btn-default"><span  data-color="1" class=" glyphicon glyphicon-road" style=""></span></a>
    <a href="#" class="btn btn-xs btn-default"><span  data-color="2" class=" glyphicon glyphicon-remove-sign" style=""></span></a>
    </div>
<?php endwhile;
$stmt->close(); ?>

$('.statusicons').on('click', function() {
    var color = $(this).data('color');
    var array = ['green', 'orange', 'red'];
    $(this).attr('style', 'color :' + array[color]);
});

3 个答案:

答案 0 :(得分:1)

可能是因为data-color返回字符串。

尝试将index转换为整数。

$('.statusicons a').on('click', function() {
  var color = parseInt($(this).data('color'));  // Convert data-color to integer to check index
  var array = ['green', 'orange', 'red'];
  $(this).attr('style', 'color :' + array[color]);
});

答案 1 :(得分:0)

使用css(),将点击事件更改为链接点击,找到该链接的跨度并为其着色

$('.statusicons a').on('click', function(e) {
    e.preventDefault();
    var color = $(this).find('span').data('color');
    var array = ['green', 'orange', 'red'];
    $(this).find('span').css('color',array[color]);

});

你不能在style属性中保存颜色的状态,在页面刷新时状态会丢失,不要忘记将js包装在document ready语句中并在动态添加状态图标时委托你的事件< / p>

答案 2 :(得分:0)

尝试css()

$(this).css('color', array[color]);
相关问题