gpt4 book ai didi

javascript - 查找动态添加元素的索引

转载 作者:搜寻专家 更新时间:2023-10-31 22:42:12 25 4
gpt4 key购买 nike

我需要能够识别单击了哪个动态添加的复选框(通过索引或名称或其他方式)。这是我在类似问题上发现的 fiddle :JSFiddle

我希望它显示为“This is the 3rd checkbox”而不只是“clicked”。这可能吗?

我试过 $(this).index() 但没有成功。

最佳答案

首先,您可以使用 index() 获取匹配集中当前元素的索引。从那里您可以使用辅助函数来格式化要显示的序号。试试这个:

$(document).on('change', '[type=checkbox]', function (e) {
alert('This is the ' + getOrdinal($(this).index('[type=checkbox]') + 1) + ' checkbox');
});

function getOrdinal(n) {
var s = ["th", "st", "nd", "rd"],
v = n % 100;
return n + (s[(v - 20) % 10] || s[v] || s[0]);
}

Example fiddle

关于javascript - 查找动态添加元素的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31246029/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com