如何使用jQuery获取select选项的自定义data-weight属性值并赋值给输入框
问题修复方案
你的代码核心问题是:event.target指向的是整个<select>下拉框元素,而非当前选中的<option>选项,因此无法获取到对应选项的data-weight属性值。以下是两种可行的修复方式:
方式一:原生JavaScript写法
$(document).on('change', '#product_title_select', function (event) { // 获取选中的option元素 const selectedOption = event.target.options[event.target.selectedIndex]; // 提取data-weight属性值并赋值给输入框 document.getElementById('weight').value = selectedOption.getAttribute('data-weight'); });
方式二:jQuery写法(更简洁)
既然你已引入jQuery,可直接利用其API简化操作:
$(document).on('change', '#product_title_select', function () { // 获取当前选中选项的data-weight值 const weightValue = $(this).find('option:selected').data('weight'); // 赋值给输入框 $('#weight').val(weightValue); });
完整可运行代码示例
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select id="product_title_select"> <option value="Select" data-weight="">Select</option> <option value="123" data-weight="ABC">Option 1</option> </select> <input type="text" id="weight" value=""> <script> // 示例使用jQuery写法 $(document).on('change', '#product_title_select', function () { const weightValue = $(this).find('option:selected').data('weight'); $('#weight').val(weightValue); }); </script>
关键说明
- 必须定位到选中的option元素才能获取
data-weight值,可通过原生options[selectedIndex]或jQuery的find('option:selected')实现 - 自定义属性
data-*可通过原生getAttribute('data-weight')获取,也可用jQuery的.data('weight')读取(后者会自动转换数据类型,如数字转为Number类型)
内容的提问来源于stack exchange,提问作者DSmit
相关产品推荐
相关产品推荐

