1

我希望显示来自“conta”、“zip、city、street_a、street_b”、“count、number”的数据,并从“contact”键创建一个下拉菜单,但这无处可去,有人可以吗解释这是如何工作的,这是我所拥有的。

<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>
4

2 回答 2

0

检查主数组元素是否为数组后,然后将主数组传递each给创建选项,而不是嵌套数组

改变:

if($.isArray(val1)){
      $.each(data,function(i2,val2){
           options += "<option value="+ val2.contact +">" + val2.contact + "</option>"
      });
}

至:

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*/

});

您缺少 first 的一些右括号each。使用浏览器控制台检查抛出的错误

于 2013-03-19T00:32:05.170 回答
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>');
        });
    }
});

演示

于 2013-03-19T00:32:22.863 回答