简体   繁体   English

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

[英]Detect when a specific <option> is selected with jQuery

I'd like jQuery to detect when the option with the id trade_buy_max is selected. 我想让jQuery检测何时选择了id为trade_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? 有任何想法吗?

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;
  }
});

What you need to do is add an onchange handler to the select : 你需要做的是为select添加一个onchange处理程序:

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

you can bind change event on its select instead, then check if option selected 您可以在其选择上绑定change事件,然后检查是否选择了选项

$("select#type").change(function () {
   if( $("option#trade_buy_max:selected").length )
   {
     // do something here
   }
});
$("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. 未经测试,但这应该有效。

Use the change event and get the id attribute of the selected option: 使用change事件并获取所选选项的id属性:

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM