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

JQuery代码无法为图表柱状条设置正确宽度求助

问题修复:JQuery遍历设置柱状条宽度时全部显示相同宽度

问题原因

  1. 全局选择器覆盖所有元素:你的代码中$(".graph-bar").width(finalSum + "%")会选中页面上所有.graph-bar元素,每次循环都会把所有柱状条的宽度设置为当前数值,最终所有条都会被最后一次循环的数值覆盖(也就是Wales对应的25%)。
  2. 无效的index变量:你定义的eq = $(this).index()获取的是.value在其父元素.entry中的位置(每个.value都是父元素的第二个子元素,所以eq始终为1),且没有用来定位对应的.graph-bar,完全起不到匹配作用。

修复后的完整代码

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
    $(".graph-box .value").each(function() {
        var num = $(this).html();
        var iNum = parseInt(num);
        var finalSum = (iNum / 1000);
        // 定位当前.value所在entry下的对应graph-bar
        $(this).closest(".entry").find(".graph-bar").width(finalSum + "%");
    });
});
</script>

<style>
* {padding:0; margin:0;}
.graph-box {border:1px solid #ccc; box-shadow:3px 3px 3px #ccc;}
.entry {display:flex; align-items:center;}
.name {width:120px; background-color:#ccc; padding:0 10px; height:30px; line-height:30px;}
.graph {flex:1; height:30px; border-bottom:1px solid #ccc;}
.graph-bar {box-sizing:border-box; background-color:#ff0000; color:#fff; border:1px solid blue; height:100%;}
</style>

<body>
    <div class="graph-box">     
        <div class="entry">
            <div class="name">England</div>
            <div class="value">817</div>
            <div class="graph"><div class="graph-bar color-1"></div></div>
        </div>
        <div class="entry">
            <div class="name">Scotland</div>
            <div class="value">500</div>
            <div class="graph"><div class="graph-bar color-1"></div></div>
        </div>
        <div class="entry">
            <div class="name">Wales</div>
            <div class="value">250</div>
            <div class="graph"><div class="graph-bar color-1"></div></div>
        </div>
    </div>
</body>

关键修复点说明

  • 使用$(this).closest(".entry")找到当前.value所在的父容器.entry,再通过find(".graph-bar")定位到该容器内对应的柱状条,确保每次只修改当前条目对应的宽度。
  • 调整了CSS样式:缩小.name宽度避免过宽,给.graph设置flex:1让其占满剩余空间,优化柱状条的显示效果。

后续避免同类问题的方法

  • 精准定位DOM元素:操作关联元素时,始终以当前遍历的元素(this)为起点,通过DOM关系方法(closest()、siblings()、find())限定作用范围,避免使用全局选择器修改所有同类元素。
  • 删除无效代码:及时清理未使用的变量(比如原代码中的eq),避免混淆逻辑。
  • 调试时用console.log()替代alert():批量遍历时代码会弹出多次弹窗,用console.log(finalSum)可以更高效地查看每个循环的数值,同时不影响页面操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 23:38:26