如何在我的情况下在<select>中获取所选选项的ID?</select>

时间:2011-04-21 06:32:25

标签: javascript jquery jquery-ui javascript-events jquery-selectors

我有一个&lt;选择&gt;字段和 index.html 中的按钮:

<select id="mylist"></select>

<input type="button" id="btn" value="update">

以下 javascript 会更新&lt; 选项选择&gt;单击按钮时的字段:

var btn=$('#btn');
btn.click(function(){
     var optionList = GET_OBJECT_LIST(); //get an array of Object, object has id & name
     var select  = $("#mylist");

     select.empty();

     for(var i=0; i<optionList.length; i++){
       select.append("<option value=" + optionList[i].id+ ">" + optionList[i].name + "</option>");
     }

});

直到现在一切都很好。

然后,我想实现以下功能:options更新后,当鼠标点击<select>字段中的选项时,我可以获取对象<所选选项的strong> id (即<option>值)。怎么做??

2 个答案:

答案 0 :(得分:2)

这可能有用(不确定它是否返回数组,所以你会发现):

$('#mylist').change(function() {
  var selected = $(this).find('option:selected');

  // Foo.
});

答案 1 :(得分:1)

我想出了以下代码,它恰好符合我的要求:

$('#mylist').change(function() {
  var selected_object_id = $(this).find('option:selected').attr('value');
  console.log(selected_object_id); //it directly returns to me the selected option represented object id
});
相关问题