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

如何获取表格动态生成select切换选项时的data-*属性值并解决报错

问题根因与解决方案

错误1:Uncaught ReferenceError: index is not defined 报错原因

你写的this.data-index不符合JS语法规则,会被解析为this.data 减去 index的运算表达式,由于你没有定义名为index的变量,直接抛出引用错误,原生DOM和jQuery都不支持这种写法读取data-*属性。

错误2:$(this).attr("data-index") 返回undefined原因

你把data-index属性绑定在<option>子元素上,但change事件回调里的this指向的是父级<select>元素,<select>本身没有加data-index属性,自然读不到值。


正确实现代码

核心逻辑:先拿到<select>当前选中的<option>元素,再读取它的data-index属性

jQuery 写法

$('#showPatientPARForm').on( 'change', 'select[name="parRating"]', function (e) {
    e.preventDefault();
    // 获取当前选中的option元素
    const selectedOpt = $(this).find('option:selected');
    // 方式1:用jQuery的data方法读取,不需要加data-前缀
    console.log('data-index值:', selectedOpt.data('index'));
    // 方式2:用attr方法直接读取属性,需要写全属性名
    console.log('data-index值:', selectedOpt.attr('data-index'));
});

原生JS 写法

$('#showPatientPARForm').on( 'change', 'select[name="parRating"]', function (e) {
    e.preventDefault();
    // 获取当前选中的option元素
    const selectedOpt = this.options[this.selectedIndex];
    // 用原生dataset读取,不需要加data-前缀
    console.log('data-index值:', selectedOpt.dataset.index);
});

额外注意事项

你动态生成option的循环条件有数组越界风险,如果paraArray是数组的话,原写法for (let i = 0; i <= paraArray; i++)应该修改为for (let i = 0; i < paraArray.length; i++),否则会读取到数组的undefined项。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 14:12:04