2016-10-05 4 views
-1

그래서 URL의 데이터를 테이블의 헤드에 추가하려고합니다. URL에서 호출 된 데이터는 문자열 목록입니다. 그래서 당신이 볼 수 있듯이 목록의 각 값을 거쳐 내 테이블의 머리 인 '데이터'에 추가하려고합니다. 하지만 코드를 실행하면 아무 것도 추가되지 않습니다. 창 경보가 각각의 문자열을 표시하기 때문에 데이터가 들어간다는 것을 알고 있습니다.JQuery : 테이블 머리에 붙이기

JQuery와 :

$(document).ready(function() { 
    $.ajax({ 
     url: 'http://..../api/Dynamic?table=table1', 
     dataType: 'Json', 
     success: function (tableResults) { 
      var count = 0; 
      $.each(tableResults, function() { 
       window.alert(this); 
       $('#data th:last-child').append('<th><a id="count">' + this + '</a></th>'); 
       count++; 
      }); 
     } 
    }); 
}); 

HTML :

<table id="data" border="1" align="center" width="95%"> 
     <thead> 
      <tr> 
      </tr> 
     </thead> 
     <tbody> 
     </tbody> 
    </table> 

어떤 제안이?

+0

당신은 ... 일에 다 th를 추가. 그건 말이되지 않습니다. –

답변

1

tableResults가 문자열의 배열이면 각 매개 변수를 직접 사용할 수 있으며 다음 스 니펫 에서처럼 count 변수를 사용하지 않아도됩니다 (append 대신 after를 사용하십시오. 새 th 요소가 따라야하고 마지막 th의 자식이 아니기 때문입니다.)) :

// 
 
// if thead does not exist 
 
// 
 
if ($('#data thead').length == 0) { 
 
    $('#data').append($('<thead/>')); 
 
} 
 

 
$.each(['email', 'address', 'country'], function (index, value) { 
 
    if ($('#data th:last-child').length == 0) { 
 
    // 
 
    // if there are no th 
 
    // 
 
    $('#data thead').append('<th><a id="count' + index + '"</a>' + value + '</th>'); 
 
    } else { 
 
    $('#data th:last-child').after('<th><a id="count' + index + '"</a>' + value + '</th>'); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 

 
<table id="data" border="1" align="center" width="95%"> 
 
    <thead> 
 
    <tr> 
 
    </tr> 
 
    </thead> 
 
    <tbody> 
 
    </tbody> 
 
</table>

+0

테이블 머리가 비어 있다면? –

+0

코드를 시도했지만 작동하지 않았습니다. –

+0

예 배열과 비슷하며 오류가 발생하지 않습니다 –