从选择框中获取ID [英] Get id from select box

查看:77
本文介绍了从选择框中获取ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个选择框,其形式如下:

I have multiple select boxes whithin a form like this:

<form action="foo" method="post" id="form">
    <select id="one">
        <option value="foo1"></option>
        <option value="foo2"></option>
        <option value="foo3"></option>
      </select>
      <select id="two">
          <option value="bar1"></option>
          <option value="bar2"></option>
          <option value="bar3"></option>
      </select>
      <select id="three">
          <option value="baz1"></option>
          <option value="baz2"></option>
          <option value="baz3"></option>
      </select>
</form>

现在,如果这三个方框中的任何一个发生变化,我想知道其中哪一个。我试着像下面那样,但我只得到第一个盒子的id。我是否必须为每个选择编写它,或者有没有办法获取更改的选择框的ID?

Now, if any of these three boxes change, I wanna know which one of them. I tried it like the following, but I only get the id of the first box. Do I have to write it for each select or is there a way to get the id of the changed select box?

$(document).ready(function() {
    $('#form').change(function() {    
        var strChosen = $('select').attr('id');    
        alert(strChosen);    
    });  
});


推荐答案

使用 this 关键字并将您的选择器更改为 $('#form select')

演示

$(document).ready(function() {
  $('#form select').change(function() {
    var strChosen = $(this).attr('id');
    alert(strChosen);
  });
});

注意:你也可以使用 .on() 更改 事件的方法

Note: You can also use .on() method for change event like

$('#form select').on('change',function() {});

有关语法的更多信息,请参阅@ sbaaaang的answer

For more information on the syntax, you can refer @sbaaaang's answer

这篇关于从选择框中获取ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆