Jquery中的关联数组与遍历每个元素

时间:2011-07-14 06:52:17

标签: javascript jquery arrays multidimensional-array associative-array

我有一个像元素

<div class="control">
      <label>&nbsp;</label>
       <input type="checkbox" id="1"><span class="controlText">Check Box</span>
        <div style="display: inline;" class="delete"><sup>x</sup></div>
        <div style="display: inline;" class="properties chkbox">Properties</div>
     </div>

此元素采用id userForm的形式 我所做的是当用户点击一个按钮时,它调用一个函数,并使用类控件搜索所有div,并获取有关该div中元素的信息。

 if($("#userForm").children().size() > 1){
        var controls = new Array();
        $('#userForm').find('div.control').each(function(index, Element)
            {
                if($(Element).find('input').attr('type') == "checkbox")
                {// If element is of type checkbox
                    var attributes = new Array();
                    attributes[type] = "checkbox";
                    attributes[name] = $(Element).find('.controlText').text().toLowerCase().split(" ").join("_")+"_"+$(Element).find('input').attr("id");
                    attributes[required] = $(Element).find('input').hasClass('required');
                    controls[index] = attributes;
                    $.each(attributes, function(key, value) {
                        // here i need to print the array. 
                        // I need a format of the arrays like
                        //  controls[0]
                        //            =>
                        //              [type] = checkbox
                        //              [name] = chk_name_1
                        //              [required] = ture
                        //          [1] 
                        //            => .....  
                        alert( "The key is '" + key + "' and the value is '" + value + "'" );

                    }); 
                }
            });
}

1 个答案:

答案 0 :(得分:0)

您的代码几乎是正确的,但存在一些问题。在为attributes数组的元素指定值的行上,您需要将元素的名称放在引号中:

attributes["type"] = "checkbox";

否则,它正在寻找一个名为type的变量,该变量不存在。

您的.each循环可以正常工作,因此您只需要以您喜欢的任何格式打印值。请注意,循环中的value是一个数组,因此要打印type,您需要:

value["type"]

您也在循环错误的集合,因此将$.each(attributes, function(key, value) {更改为$.each(controls, function(key, value) {