【问题标题】:Associative arrays in Jquery with Traversing Each ElementJquery中的关联数组遍历每个元素
【发布时间】:2011-10-05 02:13:01
【问题描述】:

我有一个类似的元素

<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 + "'" );

                    }); 
                }
            });
}

【问题讨论】:

  • 您似乎正在使用一个数组,其中为 attributes 变量指示了一个对象。 Javascript 没有“关联数组”,它的对象是名称:值对的无序集合。 Array 是 Object 的一个实例,因此由 Array 构造函数创建的数组既是数组又是具有特殊长度属性和一些方便的继承方法的对象。

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


【解决方案1】:

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

attributes["type"] = "checkbox";

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

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

value["type"]

你也循环了错误的集合,所以把$.each(attributes, function(key, value) {改成$.each(controls, function(key, value) {

【讨论】:

  • 即使我已将代码更改为 attributes["type"] = "checkbox";函数 $.each(attributes, function(key, value) { alert("键是 '" + key + "' 值是 '" + value + "'" ); });还是不行……
猜你喜欢
  • 2020-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-19
  • 2021-04-02
相关资源
最近更新 更多