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

如何使用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 14:52:11