通过jquery分配样式属性

Assign style attr through jquery

本文关键字:属性 样式 分配 jquery 通过      更新时间:2023-09-26

我试图给这些span按钮分配颜色,如果我把类放在span类里面,它有点工作,但有时它不改变颜色,而且我想要能够设置只有一个按钮为彩色。我还需要将值存储在style中,因为我想在加载页面时将其着色。

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]);
});

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

尝试将索引转换为整数。

$('.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]);
});

try css()

$(this).css('color', array[color]);

使用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属性中保存颜色的状态,状态在页面刷新时丢失,如果状态图标是动态添加的,不要忘记在document ready语句中包装你的js并委托你的事件