30

我希望 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>

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

有任何想法吗?

4

6 回答 6

49

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

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

  switch (id){
    case "trade_buy_max":
      // do something here
      break;
  }
});
于 2009-12-23T14:26:46.247 回答
10

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

$('#type').change(function(){ 
  if($(this).val() == 2){
     /* Do Something */
  }
});
于 2009-12-23T14:25:56.653 回答
4

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

$("select#type").change(function () {
   if( $("option#trade_buy_max:selected").length )
   {
     // do something here
   }
});
于 2009-12-23T14:25:29.290 回答
1
$("option#trade_buy_max").change(function () {
    opt = $(this).children("option:selected").attr('id');
    if(opt == '#trade_sell_max'){
        // do stuff
    } 
});

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

于 2009-12-23T14:26:00.227 回答
1

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

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

  if (selectedId == "trade_buy_max") {
    // do something
  }
});
于 2009-12-23T14:27:16.307 回答
0

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

于 2009-12-23T14:24:44.770 回答