You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据is_active布尔值为数组切片返回的字符串设置对应文本颜色

代码问题点

  • 入参is_active被后续赋值的数组切片字符串覆盖,原本的布尔判断条件完全失效
  • addClass是操作DOM元素的jQuery方法,普通字符串没有该API,调用会抛出错误
  • 函数最终返回空字符串,无法获取需要的切片内容

实现方案

1. 先定义对应样式类

.range {
  color: blue;
}
.transp {
  color: gray;
}

2. 修正后的JS函数

const t2_array = [5, 7, 9, 11, 13, 17, 22, 25, 26, 29, 31, 35, 36, 39, 40, 44, 55, 77];

function t2PrintSlice(beg, end, is_active) {
  // 生成数组切片字符串,不覆盖原有入参
  const resultStr = t2_array.slice(t2_array.indexOf(5), t2_array.indexOf(26)).join(', ') + ',';
  // 根据布尔参数匹配对应类名
  const activeClass = is_active ? 'range' : 'transp';
  // 返回带类名的HTML结构,插入页面后可直接生效样式
  return `<span class="${activeClass}">${resultStr}</span>`;
}

3. 调用方法

  • jQuery 插入页面示例:
// 传入true返回蓝色字符串
$('#yourContainer').html(t2PrintSlice(0, 0, true));
// 传入false返回灰色字符串
$('#yourContainer').html(t2PrintSlice(0, 0, false));
  • 原生JS 插入页面示例:
document.getElementById('yourContainer').innerHTML = t2PrintSlice(0, 0, true);

如果不需要返回HTML结构,只需要拿到文本和对应样式自行处理,可以修改函数为返回对象:

function t2PrintSlice(beg, end, is_active) {
  const resultStr = t2_array.slice(t2_array.indexOf(5), t2_array.indexOf(26)).join(', ') + ',';
  return {
    text: resultStr,
    color: is_active ? 'blue' : 'gray'
  }
}

内容的提问来源于stack exchange,提问作者EnTil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 21:27:01