【问题标题】:Setting the SELECTED attribute on a JQuery HTML select list populated from a PHP array [duplicate]在从 PHP 数组填充的 JQuery HTML 选择列表上设置 SELECTED 属性 [重复]
【发布时间】: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


【解决方案1】:

属性selected&lt;option&gt; 的一部分,而不是&lt;select&gt; 本身。您应该将代码修改为:

function update_animal_options(optionsArray) {
    $(animals_select).empty();

    $(animals_select).append(
        '<option value=' + optionsArray[i] 
        + (optionsArray[i] == current_selected? ' selected' : '') + '>' 
        + optionsArray[i] + '</option>'
    );
}

另外,总是将属性值用引号括起来是个好主意。否则,value=Some value here 之类的代码将不会按照您的预期处理。

【讨论】:

  • 我没有考虑过使用内联 if 来添加选择!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-27
相关资源
最近更新 更多