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

如何获取被点击的img-frame类子元素在父容器中的索引值

方案1:直接使用jQuery内置index()方法(适合DOM结构固定的场景)

这是最小改动你现有代码的方案,只需要修改点击回调函数即可:

function pictureClicked(e) {
    // index()不传参时默认返回当前元素在同级兄弟元素中的索引,从0开始计数
    const currentIndex = $(e.currentTarget).index();
    console.log(currentIndex);
}

另外你现有的遍历绑定代码可以简化,jQuery支持直接给批量选中的元素绑定事件,不需要手动each遍历:

// 替换原来的each绑定代码即可,效果完全一致
$('.img-frame').on('click', pictureClicked);

方案2:绑定时预存索引(适合DOM结构可能动态变化的场景)

如果后续会动态在父容器内插入/删除其他同级元素,为了避免索引值受DOM结构变动影响,可以在绑定事件时就把索引存在元素的自定义数据里:

$('.img-frame').each((i, img) => {
    // 将当前遍历的索引存入元素的data属性
    $(img).data('itemIndex', i).on('click', pictureClicked);
});
  
function pictureClicked(e) {
    const currentIndex = $(e.currentTarget).data('itemIndex');
    console.log(currentIndex);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 20:09:02