You need to enable JavaScript to run this app. 如何用jQuery实现ul下单个li点击淡出并统计已点击li数量(修复全淡出问题)
优惠活动
大模型
产品
解决方案
定价
更多

如何用jQuery实现ul下单个li点击淡出并统计已点击li数量(修复全淡出问题)

标签页li淡出与点击计数实现方案

原有代码异常根因

点击事件的回调函数中,使用全局选择器$("li")匹配全文档下所有li元素执行fadeOut(),没有限定操作对象为当前触发点击的元素,因此会出现任意li被点击时,所有li同时淡出的问题。

核心实现逻辑

要满足两个需求,只需要调整两处核心代码:

  • 点击事件中通过jQuery事件回调内置的$(this)指向当前被点击的li,仅对单元素执行淡出,不影响其他兄弟节点或其他标签页下的li
  • 在独立作用域内定义计数器,每次有li完成淡出动画时累计计数,最终输出/展示总点击数

可直接运行的完整代码

<div class="tab">
    <h2>Lobby</h2>
    <ul>
        <li>Sponsor logos are displayed correctly and all link to their relevant sponsor booths</li>
        <li>Top-left (branding) logo is displayed correctly and links to the event homepage</li>
        <li>Lecture Theatre signpost is displayed correctly and links to the Live Redirect</li>
        <li>Exhibition Hall signpost is displayed correctly and links to the event Exhibition Hall</li>
        <li>If Delegate chat is in use, ensure the Minnit chat widget is displayed correctly and working</li>
        <li>Ensure background image is appropriate for the event and displayed correctly, adjustments can be made in the branding tab CSS on the platform</li>
    </ul>
</div>

<script>
$(document).ready(function(){
    // 作用域隔离的点击计数器,避免全局变量污染
    let totalClickedLi = 0;

    $("li").click(function(){
        // 仅对当前被点击的li执行淡出
        $(this).fadeOut(300, function(){
            // 动画完成后累加计数,避免快速点击导致计数偏差
            totalClickedLi++;
            // 可将计数结果按需展示到页面任意位置,此处仅打印调试
            console.log("已点击淡出的li总数量:", totalClickedLi);
        });
    });
});
</script>

细节优化说明

  • 计数器定义在document.ready的作用域内,不会被外部脚本干扰,页面加载完成后自动从0开始累计
  • 计数操作放在fadeOut的动画回调中执行,等元素完全隐藏后再累计数量,避免用户快速点击时出现重复计数、动画未完成就计数的问题
  • 若需要把计数结果直接展示在页面上,可在对应tab的标题位置添加展示节点,计数完成后同步更新节点文本即可,例如:
<h2>Lobby <span class="li-count-text" style="font-size:0.8em;color:#666;">已完成:0</span></h2>

对应的JS累加后增加一行文本更新逻辑:

totalClickedLi++;
$(".li-count-text").text(`已完成:${totalClickedLi}`);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.14 12:36:07