jquery - 选择标记中的选项未附加在 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>
解决方案
您应该添加$(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>
推荐阅读
- python - tkinter - 致命 Python 错误:PyEval_RestoreThread:NULL tstate
- karate - Karate.print 不打印实际内容
- php - PHP - file_put_contents 文件操作
- java - 类型转换为 int 时双精度不截断
- c - 在十六进制数组中写入位
- r - 使用 dplyr/tidyverse 在 R 中的 group_by 和 summarise() 多个事物
- javascript - 使用 React Router 对导出的组件进行嵌套路由
- javascript - 单击按钮时显示/隐藏 div 并保存 Cookie
- ember.js - 我希望 Emberjs 中的每条路线都有自己的页面,当我有多个路线时,它们都会在同一页面中显示内容
- javascript - 如何重新加载/刷新 Stripe Checkout 按钮?