2016-09-26 24 views
2

どのように私は、文字列のVAR mydata="a1,a2,a3, ,a5,b1,b2,b3,b4,b5"を持っていると私は、以下のこの要素に割り当てる必要がある場合: - ?子要素に文字列配列を割り当てる方法は?

Parent Index: 0 (div classname="parts") 
.serialno="a1" 
.modelno="a2" 
.section="a3" 
.subsection=" " -empty value 
.incharge="a5" 

Parent Index: 1 (div classname="parts") 
.serialno="b1" 
.modelno="b2" 
.section="b3" 
.subsection="b4 " 
.incharge="b5" 

私がすでに知っていることは以下のような要素ストレートフォワードに文字列配列を割り当てる方法である: -

var mydata = $("#txtproduction").val(); 
       var gdata = mydata.split(',').length/5; //get how many group 



      if (gdata = 1) { 
       $.each(mydata.split(','), function (index, value) {     
        if (index == 0) { $('.serialno').val(value); } 
        if (index == 1) { $('.modelno').val(value); } 
        if (index == 2) { $('.section').val(value); } 
        if (index == 3) { $('.subsection').val(value); } 
    if (index == 4) { $('.incharge').val(value); } 
       }); 
      } 

が、要素が親の内部の子供を持っているとき、私はそれを処理する方法がわからない...

 if (gdata >1){ 
     //if more than 1 group data - how to handle loop assign value to element accondingly?? 

     } 

私を助けてください、私はすでに多くのだと思いますまだ問題を解決する方法を理解することはできません。 私の質問を読んで返信してくれてありがとう。以下のような素子構造のため

答えて

1

:コードの下

<div class="parts"> 
<input type="text" class="serialno"> 
<input type="text" class="modelno"> 
<input type="text" class="section"> 
<input type="text" class="subsection"> 
<input type="text" class="incharge"> 
</div> 
<div class="parts"> 
<input type="text" class="serialno"> 
<input type="text" class="modelno"> 
<input type="text" class="section"> 
<input type="text" class="subsection"> 
<input type="text" class="incharge"> 
</div> 

は動作するはずです:構造が異なる場合

var mydata = $("#txtproduction").val();    
var arr = mydata.split(','); 
$('.serialno').each(function(i, o)  {$(this).val(arr[$(this).parent().index(".parts")*5]);}); 
$('.modelno').each(function(i, o) {$(this).val(arr[$(this).parent().index(".parts")*5+1]);}); 
$('.section').each(function(i, o) {$(this).val(arr[$(this).parent().index(".parts")*5+2]);}); 
$('.subsection').each(function(i, o) {$(this).val(arr[$(this).parent().index(".parts")*5+3]);}); 
$('.incharge').each(function(i, o) {$(this).val(arr[$(this).parent().index(".parts")*5+4]);}); 

は、私の理解を修正してください。 チェックhere.

+0

こんにちは、この問題に関して私を助けてくれたctorと#Walfに感謝します。正直なところ、私はこの答えを見た前に問題を解決するために私自身の方法ですでに考え出していますが、私はまだあなたの両方の解決策が好きで、印があるべきです。私はあなたのコードを将来使用しようとします。助けてくれてありがとうと私は本当に感謝します。 –

1

mydataの構造を変更できますか?あなたはレコード内とレコード間で同じデリミタを持っています。レコードをセミコロンで結合する方がよいでしょう。 a1,a2,a3,a4,a5;b1,b2,b3,b4,b5;…

そうでない場合は、配列を「チャンク」する必要があります。

var myData = $("#txtproduction").val().split(','), 
    columnsPerRecord = 5, 
    record; 
while (myData.length) { 
    // iterate/create div here 
    record = myData.splice(0, columnsPerRecord); 
    $(currentDiv).find('.serialno').val(record[0]); 
    … 
} 
関連する問題