当我更改选项时,我想从表中动态创建的选择中获得data-*属性的值。我得到一个"未捕获的引用错误:索引未定义"。
创建的HTML是:
html += "<td style='width : 1%; white-space: nowrap;'><select name='parRating'>"
for (let i = 0; i <= paraArray; i++) {
html += "<option name='parRatingOption' data-index='" + i + "' value='" + parIdArray[i] + "'>" + parRatingArray[i] + "</option>"
};
html += "</select></td>";
选项更改catch是:
$('#showPatientPARForm').on( 'change', 'select[name="parRating"]', function (e) {
e.preventDefault();
alert("this.value: " + this.value);//works
alert("this.data-index: " + this.data-index);//Uncaught ReferenceError: index is not defined
});
我也试过了:
警报("this.attr("材料指数"):"+ $ () .attr("data-index");//定义
您需要确保正确定位data-attribute
,该选项的值从父选择器(select
)返回,但需要以不同的方式访问该选项本身。使用dataset
来定位数据属性
let paraArray = ['one','two','three'];
let parIdArray = ['idOne','idTwo','idThree'];
let parRatingArray = [1,2,3];
let html = '';
html += "<td><select name='parRating'>";
for (let i = 0; i < paraArray.length; i++) {
html += "<option name='parRatingOption' data-index='" + i + "' value='" + parIdArray[i] + "'>" + parRatingArray[i] + "</option>";
}
html += "</select></td>";
$('#showPatientPARForm table').append(html);
$('#showPatientPARForm').on( 'change', 'select[name="parRating"]', function (e) {
e.preventDefault();
alert("this.value: " + this.value);//works
// select the data attribute correctly:
//alert(this.options[this.options.selectedIndex].dataset.index);
alert(this.options.selectedIndex)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="showPatientPARForm">
<table></table>
</div>