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

如何让select元素选中当前已选选项时也触发页面跳转?

解决Select重复选中当前选项无法跳转的问题

问题根源

原生<select>的change事件仅在选中项实际发生变化时才会触发,所以重复选择当前已选中的选项时,事件不会执行,自然无法触发跳转。

可行方案

不再依赖change事件,改为监听用户与下拉选项的交互动作,无论选中的是不是当前项,都直接获取对应链接执行跳转。

方法一:精准捕获选项点击动作

$(document).on("mousedown", "#select", function() {
  const $select = $(this);
  // 给所有选项绑定mouseup事件,确保选中后立即触发跳转
  $select.find("option").on("mouseup", function() {
    const currentSlug = $(this).attr("data-slug");
    window.location.href = currentSlug;
    // 解绑事件,避免重复绑定导致多次触发
    $select.find("option").off("mouseup");
  });
});

方法二:简洁的延迟判断方案

如果场景简单,也可以用延迟获取选中状态的方式实现:

$(document).on("click", "#select", function() {
  const $select = $(this);
  // 延迟100ms,确保选项选中状态已完成更新
  setTimeout(() => {
    const currentSlug = $select.find("option:selected").attr("data-slug");
    window.location.href = currentSlug;
  }, 100);
});

额外提示

如果你的data-slug存在为空的可能,可以在跳转前增加判断:if (currentSlug) window.location.href = currentSlug;,避免无效跳转。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 09:06:35