2017-09-20 263 views
2

我有以下HTML /引導形式(動態生成的):循環通過HTML元素

<div id="date_fields"> 
<div class="form-group removeclass0"> 
    <div class="col-sm-6 nopadding"> 
     <div class="form-group"> 
      <input type="text" class="form-control dateKey" name="dateKey[]" value="revision"> 
     </div> 
    </div> 
    <div class="col-sm-6 nopadding"> 
     <div class="form-group"> 
      <div class="input-group"> 
       <input type="text" class="form-control dateValue" name="dateValue[]" value="2010-09-20"> 
       <div class="input-group-btn"> 
        <button class="btn btn-danger" type="button" onclick="remove_date_fields(0);"> 
         <span class="glyphicon glyphicon-minus" aria-hidden="true"></span> 
        </button> 
       </div> 
      </div> 
     </div> 
    </div> 
    <div class="clear"></div> 
</div> 
<div class="form-group removeclass1"> 
    <div class="col-sm-6 nopadding"> 
     <div class="form-group"> 
      <input type="text" class="form-control dateKey" name="dateKey[]" value="publication"> 
     </div> 
    </div> 
    <div class="col-sm-6 nopadding"> 
     <div class="form-group"> 
      <div class="input-group"> 
       <input type="text" class="form-control dateValue" name="dateValue[]" value="2008-05-21"> 
       <div class="input-group-btn"> 
        <button class="btn btn-danger" type="button" onclick="remove_date_fields(1);"> 
         <span class="glyphicon glyphicon-minus" aria-hidden="true"></span> 
        </button> 
       </div> 
      </div> 
     </div> 
    </div> 
    <div class="clear"></div> 
</div> 

這裏是的jsfiddle: https://jsfiddle.net/mleontenko/mmk9zo4L/

我需要通過這種形式和存儲環dateKey和dateValue配對成如下所示的數組:

[ 
    { 
     "dateKey":"revision", 
     "dateValue":"2010-09-20" 
    }, 
    { 
     "dateKey":"publication", 
     "dateValue":"2008-05-21" 
    } 
] 

使用jQuery或普通JavaScript來做到這一點的最佳方式是什麼?

+0

請界定 「_The best_」。 – Teemu

+0

任何簡單的解決方案,:) :) –

+0

但是,這不是「最好的」,那是「任何」..? – Teemu

回答

4
$(document).ready(function() { 
    var keys = []; 
    var values = []; 
    var res = []; 
    $.each($("#date_fields").find(".dateKey"), function(i, key) { 
      keys[i] = $(".dateKey:eq("+i+")").val(); 
    }); 

    $.each($("#date_fields").find(".dateValue"), function(i, value) { 
     values[i] = $(".dateValue:eq("+i+")").val(); 
    }); 


    $.each($("#date_fields").find(".dateValue"), function(i) { 
     res[i] = {"dateKey" : keys[i], "dateValue": values[i]}; 
    }); 
    $("#result").text(JSON.stringify(res)); 
}); 

的jsfiddle:Working js fiddle