我有这段代码:
function select(cities, country) {
$('<div class="btn-group "><button type="button" id="forecast"
data- toggle="modal" data-target="#myModal" name="forecast"
class="btn btn-primary pull-right" >Show Me The Forecast</div>').insertAfter('.btn-group');
$('#cities').html(' <label for="cities">Select City</label>
<select name="cities" id="city" class="form-control">' +
'<option disabled selected value> -- select an option -- </option>' +
cities.map(function (city) {
return '<option value="' + city + '">' + city + '</option> ';
}).join('') + '</select>'
);
var city = $("#city option:selected").val();
console.log(city);
}
我想获取上面选择元素的特定值,但是每一个时刻它取第一个值并将其存储到city
变量
答案 0 :(得分:0)
我想你想要这个演示中的结果:
select(['city1', 'city2', 'city3'], 'country1');
function select(cities, country) {
$('<div class="btn-group "><button type="button" id="forecast" data- toggle="modal" data-target="#myModal" name="forecast" class="btn btn-primary pull-right" >Show Me The Forecast</div>').insertAfter('.btn-group');
$('#cities').html(' <label for="cities">Select City</label><select name="cities" id="city" class="form-control">' +
'<option disabled selected value> -- select an option -- </option>' +
cities.map(function(city) {
return '<option value="' + city + '">' + city + '</option> ';
}).join('') + '</select>'
);
var city = $('#city option:selected').val();
console.log(city) // initially selected city (none)
$("#city").on('change', function() {
city = $(this).find('option:selected').val();
console.log(city); // changed option for new selected city
});
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="cities">
</div>
<div class="btn-group">
</div>
&#13;