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

Vue.js/jQuery实现选中下拉选项时更新链接href

嘿,这需求太常见啦,给你整了Vue.js和jQuery两种简单直接的实现方案,完全不用搞那种麻烦的循环遍历,看你顺手用哪个~

Vue.js 实现方案

Vue的双向绑定天生就适合干这事,代码清爽得很:

首先是模板部分:

<div id="app">
  <select v-model="selectedUrl">
    <option value="https://example.com/page1">页面1</option>
    <option value="https://example.com/page2">页面2</option>
    <option value="https://example.com/page3">页面3</option>
  </select>

  <a :href="selectedUrl" target="_blank">跳转链接</a>
</div>

然后是脚本部分(Vue 3写法,Vue 2只需调整下结构即可):

const { createApp } = Vue;
createApp({
  data() {
    return {
      selectedUrl: 'https://example.com/page1' // 设置默认选中的URL
    }
  }
}).mount('#app');

原理超简单:v-model会自动把select的选中值同步到selectedUrl变量里,而链接的:href又绑定了这个变量,选中选项的瞬间href就自动更新了,全程不用手动操作DOM,Vue帮你搞定一切~

如果是多个select对应多个链接的情况,你可以把每个条目做成组件,或者用数组存每个条目的选中值,示例如下:

<div id="app">
  <div v-for="(item, index) in linkItems" :key="index">
    <select v-model="item.url">
      <option :value="opt.value" v-for="opt in item.options" :key="opt.value">{{opt.text}}</option>
    </select>
    <a :href="item.url" target="_blank">{{item.linkText}}</a>
  </div>
</div>

脚本里的data:

data() {
  return {
    linkItems: [
      {
        url: 'https://example.com/page1',
        linkText: '跳转页面1',
        options: [
          {value: 'https://example.com/page1', text: '页面1'},
          {value: 'https://example.com/page2', text: '页面2'}
        ]
      },
      // 可以添加更多条目...
    ]
  }
}
jQuery 实现方案

如果你更习惯用jQuery,那也很简单,监听select的change事件就行:

基础版(单个select对应单个链接):

<select id="urlSelect">
  <option value="https://example.com/page1">页面1</option>
  <option value="https://example.com/page2">页面2</option>
  <option value="https://example.com/page3">页面3</option>
</select>

<a id="targetLink" href="https://example.com/page1" target="_blank">跳转链接</a>
$('#urlSelect').on('change', function() {
  // 获取选中的URL值
  const selectedUrl = $(this).val();
  // 更新链接的href属性
  $('#targetLink').attr('href', selectedUrl);
});

要是有多个select和对应链接,可以给它们加关联的标识,比如用data属性绑定对应链接的id:

<select class="url-select" data-target-link="link1">
  <option value="https://example.com/page1">页面1</option>
  <option value="https://example.com/page2">页面2</option>
</select>
<a id="link1" href="https://example.com/page1" target="_blank">跳转链接1</a>

<select class="url-select" data-target-link="link2">
  <option value="https://example.com/pageA">页面A</option>
  <option value="https://example.com/pageB">页面B</option>
</select>
<a id="link2" href="https://example.com/pageA" target="_blank">跳转链接2</a>
$('.url-select').on('change', function() {
  const selectedUrl = $(this).val();
  // 获取对应链接的id
  const targetLinkId = $(this).data('target-link');
  // 更新对应链接的href
  $('#' + targetLinkId).attr('href', selectedUrl);
});

这样不管有多少个条目,都能精准对应更新,完全不用遍历所有选项,简单高效~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:49:18