选择<;选项>;使用JQuery从html

选择<;选项>;使用JQuery从html,jquery,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&

我有点被这个代码卡住了。我正在尝试检索选项文本

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>
HTML代码
$(文档).ready(函数(){
对于(i=0;i
我无法检索所选值。因此我使用了
$(“#名称”)
作为选择器,因为
$(“#名称选项”)
不起作用。 我做错了什么?

试试看

$("#names option:selected").text();
或者在你的代码中

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

您需要使用
change()
处理程序,并且可以直接从
本身获取值

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

在选择过程中,您将有几个单击事件,这是一个原因
click()
不会有太大帮助的问题

一个有趣的问题,建议在哪里使用“$(this).find(':selected').text();”?在追加之后还是在追加之前?之后。但正如charlietfl指出的,最好使用更改事件而不是单击。