【问题标题】:Javascript give array Key a name while doing an array 'push'Javascript 在执行数组“推送”时为数组键命名
【发布时间】:2014-01-28 12:58:48
【问题描述】:

我有 3 组单选按钮,每组包含多个单选按钮。在 bootstrap3 中为每个组使用 data-toggle="buttons" 时,我可以确保每个组只选择一个答案。到目前为止一切都很好。

下面的函数在点击事件上触发并返回所选项目的值。我的问题是如何处理存储在数组values 中的返回值,并为每个键指定一个与按钮组对应的名称。

假设我选择 Red + small + Circle 然后 getValues 将返回 key=> 值:

  • [0] => 红色
  • [1] => 小
  • [2] => 圆圈

现在,如果我选择 small + Circle

  • [0] => 小
  • [1]=> 圈子

这些值是按照选择的顺序存储的,我试图获取这些值以根据选择构建查询..

我希望以这种格式存储值的位置:

  • [颜色] =>x
  • [大小] => y
  • [形状] => z

d

<input type="radio" name="color" value="red"/> Red     /// Grp 1 Color
<input type="radio" name="color" value="blue"/> Blue
<br/>
<input type="radio" name="size" value="small"/> small   /// Grp2  Size
<input type="radio" name="size" value ="Large"/> Large
<br/>
<input type="radio" name="shape" value="circle"/> Circle  /// Grp3 Shape
<input type="radio" name="shape" value="square"/> Square


function getValues(){

var values = [];
for(var x = 0; x < radios.length; x++){
    if(radios[x].type == "radio" && radios[x].checked){
       values.push(radios[x].value);
    }
}
return values;

}

$( "#Btn" ).click(function() {
      var x = getValues();

$.each(x, function(k, v) {

//display the key and value pair
      alert(k + ' is ' + v);

});

谢谢

【问题讨论】:

  • 数组没有你想要的对象的索引名称
  • javascript中没有关联数组
  • 您也许可以将值属性指定为color:redsize:small 等,而不仅仅是redsmall 等。然后通过处理您的内容轻松拆分并拥有自己的密钥得到。
  • 谢谢,我不知道 javascript 中没有关联数组...@Chavan - 感谢您提供有用的链接

标签: javascript jquery


【解决方案1】:

试试这个。

LIVE DEMO

我认为关联数组在 Javascript 中是可能的。

http://www.i-programmer.info/programming/javascript/1441-javascript-data-structures-the-associative-array.html

<input type="radio" name="color" class="radioGrp" value="red"/> Red  
<input type="radio" name="color" class="radioGrp" value="blue"/> Blue
<br/>
<input type="radio" name="size" class="radioGrp" value="small"/> small
<input type="radio" name="size" class="radioGrp" value ="Large"/> Large
<br/>
<input type="radio" name="shape" class="radioGrp" value="circle"/>circle
<input type="radio" name="shape" class="radioGrp" value="square"/>square

<input type='button' id="Btn" />


function getValues(){

var values = [];
var radios = document.getElementsByClassName("radioGrp");
    console.log(radios);

for(var x = 0; x < radios.length; x++){
    if(radios[x].type == "radio" && radios[x].checked){
       values[radios[x].name] = (radios[x].value);
    }
}
  return values;
}

$("#Btn").click(function() {
      var x = getValues();

     alert(x["color"]);
     alert(x["size"]);
     alert(x["shape"]);

     for(var prop in x ){
       alert( prop + " is " + x[prop] );
     }

});

您不能将 $.each 用于关联数组以获取更多详细信息http://bugs.jquery.com/ticket/4319

【讨论】:

    【解决方案2】:

    如前所述,数组在 JS 中的处理方式不同。你真正想要的是一个哈希表......这是 JS 只是一个对象(有点)。

    您可以使用的一种技术是创建一个类数组对象,该对象将名称作为键和索引。

    需要注意的是,这不是一个功能齐全的类数组对象,因为它没有实现推送、弹出、切片等...

    var values = {},
        length = 0;
    
    for(var x = 0; x < radios.length; x++){
        if(radios[x].type == "radio" && radios[x].checked){
            //Assign the name as a key on the object
            values[radios[x].name] = radios[x].value;
    
            //Also assign the index as a key
            values[x] = radios[x].value;
    
            length += 1;
        }
    }
    
    values.length = length;
    
    return values;
    

    那么这对你有什么作用呢?

    嗯,它允许您通过键访问各个项目:

    values['bob'];
    

    它还允许您通过索引访问它们:

    values[0];
    

    更好的是,您可以使用普通的 for 循环遍历它们:

    for(var i = 0; i < values.length; i++){
       //I act just like an array!!
       values[i];
    }
    

    【讨论】:

    • 非常感谢乔希。只是将索引分配为键的部分不应该是 values[x] = radios[x].name;而是?
    • @user3003977 - 我想这取决于您是否想要其中的名称或值。
    【解决方案3】:

    请使用以下代码:

        function getValues(){
    
        var values = [];
        for(var x = 0; x < radios.length; x++){
            if(radios[x].type == "radio" && radios[x].checked){
                var tmp={};
                tmp[radios[x].name]=radios[x].value;  
               values.push(tmp);
            }
        }
        return values;
    
        }
    
        $( "#Btn" ).click(function() {
              var x = getValues();
    
        $.each(x, function(k, v) {
    
        //display the key and value pair
              alert(k + ' is ' + v);
    
        });
    

    【讨论】:

      【解决方案4】:

      下面的示例代码将所有选中的复选框作为数组获取

      // A function that return an array with the selected items
      function getSelected() {
      
        var selected = [];
      
        var checkboxes = $('input[type=checkbox]:checked');
      
        for(var i = 0; i < checkboxes.length; i++){
           if(checkboxes[i].checked){
              selected.push(checkboxes[i].value);
           }
        }
      
        return selected;
      
      }
      

      请注意,这适用于 jQuery。

      【讨论】:

        【解决方案5】:

        您的代码可能看起来像这样:

        <script>
        function getValues() {
          var values={};
          var inputs = document.getElementsByTagName("input");
          console.log(inputs);
          for (var i=0;i<inputs.length;++i) 
             if (inputs[i].type==="radio" && inputs[i].checked) 
                values[inputs[i].name]=inputs[i].value;
         console.log(values);
        }
        </script>
        <button onclick="getValues()">Hit me</button>
        

        我知道这不是 jQuery - 但你应该能够转换它:)

        这将创建一个对象,您可以从中按正确顺序选择键值对:

        [ values.color||"default", values.size||"default", values.shape||"default" ]
        

        【讨论】:

          猜你喜欢
          • 2011-12-10
          • 2013-05-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-12-22
          • 2012-03-30
          • 1970-01-01
          • 2020-05-11
          相关资源
          最近更新 更多