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

多区块最长字符串查找弹窗显示异常求助

问题排查与解决方案

嗨,我来帮你搞定这个问题~

问题根源

你这段代码的核心bug在于遍历子元素时没有限定范围:当你在$('.parent').each()的回调里执行$('.child').each()时,这个选择器会选中页面上所有带.child类的元素,而不是当前正在处理的.parent下面的子元素。所以第一次遍历第一个.parent的时候,会把第二个.parent里的beautiful也算进去,导致两次弹窗都显示beautiful,完全偏离了你的预期。

修正后的代码

只需要把全局的.child选择器改成基于当前父元素的查找即可,用$(this).find('.child')来限定范围,同时建议用let/const声明变量避免全局污染:

$('.parent').each(function() { 
    let longest = ""; 
    $(this).find('.child').each(function() { 
        const textChild = $(this).text(); 
        if (textChild.length > longest.length) { 
            longest = textChild; 
        } 
    }); 
    alert(longest) 
}) 

完整可运行代码

把修正后的JS和你的HTML结合起来,就能得到符合预期的效果:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 
<div class="parent"> 
    <div class="child">hello</div> 
    <div class="child">wonderful</div> 
    <div class="child">world</div> 
</div> 
<div class="parent"> 
    <div class="child">hello</div> 
    <div class="child">beautiful</div> 
    <div class="child">world</div> 
</div>

这样修改后,第一个弹窗会显示wonderful,第二个显示beautiful,完全符合你的需求啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 14:47:46