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

jQuery如何动态获取被点击div的nth-of-type序号实现文本替换

问题

有一组div元素:

<div>Hello</div> 
<div>click</div>
<div>here</div>
...
<div>The end</div>

想要实现点击逻辑:点击不同div时,根据该div的nth-of-type序号,从数组outputData中取出对应文本替换该div内容,代码示例如下:

//var n = which div number.
var outputData = ['first', 'second', 'third', ..., 'thank you'];
$('div').click(function() {
    // where 'n' should be the nth-of-type number of the div that's been clicked.
    $(this).text(outputData[n]);
});

但无法动态获取被点击div的nth-of-type序号以返回正确结果。已查阅相关资料了解过:eq()选择器,但资料均为硬编码序号,未涉及动态获取nth-of-type的方法,请问如何实现该需求?

解决方案

方法1:使用jQuery的.index()方法

.index()方法如果不带参数,会返回当前元素在同辈元素中的位置(从0开始计数),刚好对应数组的索引:

var outputData = ['first', 'second', 'third', 'thank you'];
$('div').click(function() {
    var n = $(this).index();
    $(this).text(outputData[n]);
});

如果这些div有其他非div类型的同辈元素,只想针对div类型的同辈元素计数,给.index()传入选择器参数即可:

var n = $(this).index('div');

方法2:原生DOM方式模拟nth-of-type计数

如果需要严格匹配CSS中nth-of-type的规则(仅统计同标签类型的前序同辈元素),可以通过遍历前序元素手动计数:

var outputData = ['first', 'second', 'third', 'thank you'];
$('div').click(function() {
    var count = 0;
    var prev = this.previousElementSibling;
    while (prev) {
        if (prev.tagName === 'DIV') {
            count++;
        }
        prev = prev.previousElementSibling;
    }
    $(this).text(outputData[count]);
});

方法3:预先绑定索引属性

初始化时给每个div存储对应索引,点击时直接读取,性能更优:

var outputData = ['first', 'second', 'third', 'thank you'];
$('div').each(function(index) {
    $(this).data('index', index);
}).click(function() {
    var n = $(this).data('index');
    $(this).text(outputData[n]);
});

内容的提问来源于stack exchange,提问作者Mm-Art-In

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 20:12:15