我希望显示“conta”,“zip,city,street_a,street_b”,“count,number”中的数据,并从“联系人”键创建一个下拉菜单,但是这里没有,有人可以解释这是如何工作的,这是我得到的东西。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery</title>
<!-- script type='text/javascript' href='https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'></script -->
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
data = [
{"conta":"13356","name":"MISS Two"},
{"zip":"01111","city":"NASHUA, MA","street_a":"10 MAIN ROAD SQUARE","street_b":"Nothing"},
{"count":"544","number":"250"},
[
{"contact":"Mark Bre"},
{"contact":"Mary Lou"},
{"contact":"John Ton"},
{"contact":"Carls Des"},
{"contact":"Carlos Drt"}
]
]
$('body').append('<select id="dynamicSelect"></select>');
var options="";
$.each(data,function(i1,val1){
if($.isArray(val1)){
$.each(data,function(i2,val2){
options += "<option value="+ val2.contact +">" + val2.contact + "</option>"
});
}
}
$('#dynamicSelect').append(options);
</script>
</head>
<body>
The Select:<select id="dynamicSelect">
<option value="option value" selected="selected">option html</option>
</select>
</body>
</html>
答案 0 :(得分:0)
检查主数组元素是否为数组后,将主数组传递给each
以创建选项,而不是嵌套数组
变化:
if($.isArray(val1)){
$.each(data,function(i2,val2){
options += "<option value="+ val2.contact +">" + val2.contact + "</option>"
});
}
TO:
if($.isArray(val1)){
/* loop over "val1"*/
$.each(val1,function(i2,val2){
options += "<option value="+ val2.contact +">" + val2.contact + "</option>"
});
}
此外,您需要将代码包装在docment.ready
中,代码在select
代码存在之前触发
在
中覆盖所有代码$(function(){
/* run code here*/
});
您错过了第一个each
的一些结束括号。使用浏览器控制台检查引发的错误
答案 1 :(得分:0)
首先,您的JS代码中存在一些错误。
)
.each()
的内部调用应该遍历val1
而不是data
再次<强> JS 强>
// Dynamically add a label for the select to the body
var label = $('<label id="dynamicSelectLabel" for="dynamicSelect">The Select</label>').appendTo('body');
// Dynamically add the select to the body
var select = $('<select id="dynamicSelect"></select>').appendTo('body');
// For each value in the data array
$.each(data, function (i1, val1) {
// If the value is an array
if ($.isArray(val1)) {
// For each value in the contact array
$.each(val1, function (i2, val2) {
// Add an option to the select with the contact name and value
select.append('<option value=' + val2.contact + '>' + val2.contact + '</option>');
});
}
});
<强> DEMO 强>