Javascript 检测何时使用 jQuery 选择了特定的 <option>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1953063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:02:42  来源:igfitidea点击:

Detect when a specific <option> is selected with jQuery

javascriptjqueryeventsselectoption

提问by Philip Morton

I'd like jQuery to detect when the option with the id trade_buy_maxis selected.

我希望 jQuery 检测何时选择了带有 idtrade_buy_max的选项。

$(document).ready(function() {
    $("option#trade_buy_max").select(function () {
        //do something
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<select name='type' id='type'>
    <option id='trade_buy' value='1' selected='selected'>Buy</option>
    <option id='trade_buy_max' value='1'>Buy max</option>
    <option id='trade_sell' value='2'>Sell</option>
    <option id='trade_sell_max' value='2'>Sell max</option>
</select>

I've tried the following, but it doesn't seem to work.

我尝试了以下方法,但似乎不起作用。

Any ideas?

有任何想法吗?

回答by Ryan

This works... Listen for the change event on the select box to fire and once it does then just pull the id attribute of the selected option.

这有效...监听选择框上的更改事件以触发,一旦触发,只需拉出所选选项的 id 属性。

$("#type").change(function(){
  var id = $(this).find("option:selected").attr("id");

  switch (id){
    case "trade_buy_max":
      // do something here
      break;
  }
});

回答by Justin Swartsel

What you need to do is add an onchangehandler to the select:

您需要做的是将onchange处理程序添加到select

$('#type').change(function(){ 
  if($(this).val() == 2){
     /* Do Something */
  }
});

回答by Anwar Chandra

you can bind changeevent on its select instead, then check if option selected

您可以change在其选择上绑定事件,然后检查是否选择了选项

$("select#type").change(function () {
   if( $("option#trade_buy_max:selected").length )
   {
     // do something here
   }
});

回答by CMS

Use the changeevent and get the idattribute of the selected option:

使用change事件并获取id所选选项的属性:

$('#type').change(function () {
  var selectedId = $('option:selected', this).attr('id');

  if (selectedId == "trade_buy_max") {
    // do something
  }
});

回答by inkedmn

$("option#trade_buy_max").change(function () {
    opt = $(this).children("option:selected").attr('id');
    if(opt == '#trade_sell_max'){
        // do stuff
    } 
});

Untested, but that should work.

未经测试,但这应该有效。

回答by Amr Elgarhy

Change .select to .change and put space before #

将 .select 更改为 .change 并在 # 前放置空格