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

如何用jQuery检测下拉框选中值是否包含Misc文本?

解决下拉框值包含"Misc"的检测问题

嗨,我来帮你搞定这个小问题~你之前的代码里用了~=,这个其实是CSS属性选择器里用来匹配包含指定独立单词的属性值的语法,但在JavaScript的条件判断里不能直接这么用,这就是代码没生效的原因啦。

下面给你几个可行的解决方案:

方案1:用includes()方法(直观简洁,ES6+支持)

这个方法是最直接的,它会检查字符串中是否包含指定的子串,只要有"Misc"就会返回true:

$(document).ready(function(){
  $("[id^='select_debit']").on('change', function() {
    if (this.value.includes('Misc')) {
      // 这里放你的code A
      console.log("选中了包含Misc的选项");
    } else {
      // 这里放你的code B
      console.log("选中的选项不包含Misc");
    }
  });
});

方案2:用indexOf()方法(兼容老浏览器)

如果需要兼容ES6之前的老浏览器,indexOf()是个不错的选择,它会返回子串第一次出现的索引,找不到就返回-1:

$(document).ready(function(){
  $("[id^='select_debit']").on('change', function() {
    if (this.value.indexOf('Misc') !== -1) {
      // run code A
      console.log("选中了包含Misc的选项");
    } else {
      // run code B
      console.log("选中的选项不包含Misc");
    }
  });
});

方案3:用正则表达式(精准匹配独立单词)

如果需要确保匹配的是独立的"Misc"单词(比如不想匹配像"Miscellaneous"这种包含Misc的长单词),可以用正则的单词边界\b:

$(document).ready(function(){
  $("[id^='select_debit']").on('change', function() {
    // \b表示单词边界,确保Misc是独立的单词
    const miscPattern = /\bMisc\b/;
    if (miscPattern.test(this.value)) {
      // run code A
      console.log("选中了包含独立Misc单词的选项");
    } else {
      // run code B
      console.log("选中的选项不符合要求");
    }
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 06:23:37