我有以下代码加载一个xml文件来填充下拉列表。我想将选定的选项文本放入变量中。我已经获得了选择的价值而不是文本。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" media="all" href="style.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
type: "GET",
url: "make10.xml",
dataType: "xml",
success: function(xml) {
var select = $('#mySelect');
var optionsHtml = new Array();
$('make', xml).each(function(){
var value = $(this).attr('value');
var label = $(this).text();
optionsHtml.push( "<option class='ddindent' value='"+ value +"'>"+label+"</option>");
});
optionsHtml = optionsHtml.join('');
select.append(optionsHtml);
select.children(":first").text("Select Make").attr("selected",true);
}
});
$('#mySelect').change(function() {
var val=$(this).val();
alert(val);
});
});
</script>
</head>
<body>
<div id="page-wrap">
<select id="mySelect">
<option>loading</option>
</select>
</div>
</body>
</html>
答案 0 :(得分:2)
要获取所选<option>
的文字,您可以使用:selected
和.text()
,如下所示:
$("#mySelect :selected").text();
(注意空间,这是一个孩子,所以这很重要)
或者,在您当前的.change()
处理程序中,它看起来像这样:
$(this).children(":selected").text();
答案 1 :(得分:1)
var selectedOptionValue = $('#mySelect:selected').val();
var selectedOptionText = $('#mySelect:selected').html();