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

如何在选中下拉框占位符时禁用onClick事件?

问题分析

你当前的核心问题有两个:

  • <a> 标签本身不支持 disabled 属性,所以设置 document.getElementById("zodiacchoice").disabled = true 完全无效
  • 判断逻辑仅检查了第一个下拉框的占位符,未覆盖“任一占位符选中”的场景
解决方案

修改点击事件函数,通过阻止默认跳转行为实现需求,同时完善判断逻辑覆盖两个下拉框:

步骤1:更新HTML的点击事件传递

将 <a> 标签的 onclick 改为传递事件对象:

<a id="zodiacchoice" href="#" onclick='GotoLink(event)'> 
  <h1>GO</h1> 
</a>

步骤2:修改JavaScript函数

function GotoLink(e) {
  var sel = $('.zodiac-me option:selected').text();
  var sel2 = $('.zodiac-them option:selected').text();
  
  // 检查任一下拉框选中占位符
  if (sel === 'Your Sign' || sel2 === 'Their Sign') {
    e.preventDefault(); // 阻止链接的默认跳转行为
    return; // 终止函数执行
  }
  
  // 验证通过,设置跳转链接
  document.getElementById("zodiacchoice").href = '/' + sel + '/' + sel + '-vs-' + sel2;
}

额外优化方案(可选)

如果不想依赖 <a> 标签的默认跳转,可直接用JS控制页面跳转,同时将 <a> 改为普通元素,逻辑更清晰:

HTML修改:

<div class="zodiacs" id="gobutton">
  <h1 id="zodiacchoice" style="cursor: pointer;">GO</h1>
</div>

JavaScript修改:

document.getElementById("zodiacchoice").addEventListener('click', function() {
  var sel = $('.zodiac-me option:selected').text();
  var sel2 = $('.zodiac-them option:selected').text();
  
  if (sel === 'Your Sign' || sel2 === 'Their Sign') {
    return; // 不执行跳转
  }
  
  // 直接跳转
  window.location.href = '/' + sel + '/' + sel + '-vs-' + sel2;
});

这样可彻底避免 <a> 标签默认行为的干扰,逻辑更可控。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 02:23:11