使用JQuery </option>从html中选择<option>

时间:2014-10-15 23:24:56

标签: jquery

我在这里遇到了这个代码。我正在尝试检索选项文本。

HTML code

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>

  $(document).ready(function() { 
     for(i=0; i<list.length; i++) { // assume list[i] contains different names
        var name_options = $('<option>' + list[i] + '</option>');
        $('#names').append(name_options);
     }

 /* I want to retrieve data when a particular option is selected. But this doesnt work*/
 $('#names').click(function(){
  var val = $(this).find(':selected').html();
 });

});

</script>
</head>
<body>
 <select id='names' class='combobox'>
  !-- options for names go here --> 
 </select>
</body>
</html>

我无法检索所选值。因此我使用$("#names")作为我的选择器,因为$("#names option")不起作用。 我在这里做错了什么?

2 个答案:

答案 0 :(得分:1)

尝试

$("#names option:selected").text();

或在您的代码中

$(this).find(':selected').text();

答案 1 :(得分:1)

您想使用change()处理程序,您可以直接从<select>本身获取值。

 $('#names').change(function(){
    var val = $(this).val();
 });

在选择过程中,您将有几个点击事件,这是click()赢得很多帮助的一个原因

相关问题