这是我的代码:
<body>
<div id="players" style="display:block">
22
</div>
<select class="form-control playerDD" style="font-weight: normal" name="player_1" id="player_1">
<option value="default">Select a player</option>
<optgroup label="Available Players">
<option value="22">John Smith</option>
<option value="23">Jane Smith</option>
<option value="24">Sam Smith</option>
</optgroup>
<optgroup label="Unavailable Players">
<option value="25">John Smith 2</option>
<option value="26">Jane Smith 2</option>
<option value="27">Sam Smith 2</option>
</optgroup>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
var foo = $("#players").text();
alert(foo); // Getting the right value and type
//foo = "22"; // This will work!
$("#player_1").val(foo); // Does not work
alert($('#player_1').val()); // Getting null
</script>
</body>
问题:我正在尝试根据div(id:players)中的值设置下拉列表(id:player_1)的值。我能够正确读取值但无法设置它。在JavaScript中,如果我硬编码foo的值,它就可以了!
这是jsfiddle:https://jsfiddle.net/4w1ack9f/2/
答案 0 :(得分:0)
$( document ).ready(function() {
$('#player_1').val(parseInt($('#players').text()));
});