You need to enable JavaScript to run this app. 如何使用data-attr属性在select下拉框中实现锚点跳转功能
优惠活动
大模型
产品
解决方案
定价
更多

如何使用data-attr属性在select下拉框中实现锚点跳转功能

问题原因

你的原有写法存在两个错误:

  • this在select的onchange事件中指向的是<select>元素本身,不是你选中的<option>子元素,无法直接拿到option上的自定义属性
  • 原生JavaScript没有attr()方法,这个是jQuery的专属语法,直接在原生事件里调用会报未定义错误

解决方法

方法1:直接修改内联onchange代码(最快适配现有代码)

把select的onchange属性改成如下写法即可正常运行:

<select class="form-select name" onchange="location = this.options[this.selectedIndex].dataset.anchor;">
    <option value="Naam" selected>Naam</option>             
    <option class="" data-anchor="index.php?name=John" value="John">John</option>
    <option class="" data-anchor="index.php?name=Susan" value="Susan">Susan</option>    
</select>

代码说明:

  • this.options 可以获取到select下所有的option节点
  • this.selectedIndex 可以拿到当前选中option的索引
  • dataset.anchor 是原生JS获取data-*自定义属性的标准写法,对应你定义的data-anchor属性

方法2:事件监听写法(符合结构逻辑分离规范,更推荐)

如果不想把JS逻辑写在HTML标签里,可以单独绑定事件:

<select class="form-select name" id="nameSelect">
    <option value="Naam" selected>Naam</option>             
    <option class="" data-anchor="index.php?name=John" value="John">John</option>
    <option class="" data-anchor="index.php?name=Susan" value="Susan">Susan</option>    
</select>

<script>
document.getElementById('nameSelect').addEventListener('change', function() {
    const selectedOption = this.options[this.selectedIndex]
    const jumpUrl = selectedOption.dataset.anchor
    // 避免选中未设置data-anchor的选项时跳转出错
    if (jumpUrl) location.href = jumpUrl
})
</script>

兼容jQuery写法(如果项目已引入jQuery可直接使用)

$('.form-select.name').on('change', function() {
    const jumpUrl = $(this).find('option:selected').data('anchor')
    if (jumpUrl) location.href = jumpUrl
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 17:18:02