【发布时间】:2018-05-14 16:33:24
【问题描述】:
我正在遍历数组中的项目列表。通过 JQuery 将这些选项输出到 html SELECT。
我想将数组中的当前项与之前选择的变量进行比较,并将<option> 属性设置为selected。
但是添加属性失败。
我做错了什么?
//PHP
$myAnimalArray = some filled array();
$s_current_selected = "Zebra";
//一些 HTML 表单
<select class="form-control" id="animals_select" name="animals_select"></select>
JQuery
<script type="text/javascript">
$(document).ready(function () {
let animal_array = <?php echo json_encode($myAnimalArray); ?>;
let animals_select = document.getElementById("animals_select");
let current_selected = "<?php echo $s_current_selected; ?>";
update_animal_options(animal_array);
function update_animal_options(optionsArray) {
$(animals_select).empty(); //remove any prior entries
for (let i = 0; i < optionsArray.length; i++) {
$(animals_select).append('<option value=' + optionsArray[i] + '>' + optionsArray[i] + '</option>');
// HERE IS WHERE MY PROBLEM IS
if (optionsArray[i] == current_selected) {
$(animals_select).attr('selected', 'selected');
}
}
}
});
</script>
【问题讨论】:
-
您可以将
$(animals_select)更改为$("#animals_select"),使其更像jquery。然后摆脱let语法。 -
用户
$(animals_select).prop('selected', true);
标签: javascript php jquery html arrays