首页 > 解决方案 > 选择标记中的选项未附加在 jquery 中

问题描述

下面选择标记中的选项属性未在页面加载时附加。下面是我使用的代码。我不知道我面临的问题是什么。

<select id="cuisineList" style="width: 200px;height: 30px;"></select>
  <script type="text/javascript">

    selectValues = { "1": "test1", "2": "test2" }

       var options = '';
       $.each(selectValues, function(key, value) {   
           options += '<option value="'+key+'">'+value+'</option>';
        });

       $("#cuisineList").append(options);

    </script>

标签: jquery

解决方案


您应该添加$(document).ready(function(){})以确保在运行 jQuery 代码之前加载文档。

演示

$(document).ready(function() {
  selectValues = {
    "1": "test1",
    "2": "test2"
  }

  var options = '';
  $.each(selectValues, function(key, value) {
    options += '<option value="' + key + '">' + value + '</option>';
  });

  $("#cuisineList").append(options);

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="cuisineList" style="width: 200px;height: 30px;"></select>


推荐阅读