JQuery HTML테이블 - 위키테이블 변환

jQuery HTML테이블 - 위키테이블 변환

1 예제1: 기본[ | ]

<style>
th, td, pre { border: 1px solid #000; }
</style>

<table id='mytable'>
  <tr><th>#</th><th>Num</th></tr>
  <tr><td>1</td><td>One</td></tr>
  <tr><td>2</td><td>Two</td></tr>
</table>

<hr>
<pre id='result'></pre>

<script src="//code.jquery.com/jquery.min.js"></script>
<script>
var wiki="{| class='wikitable'\n";
$('#mytable').each(function() {
  $(this).find('tr').each(function () {
    wiki += '|-\n';
    $(this).find('th').each(function () {
      wiki += '! ' + $(this).text() + ' ';
    });
    $(this).find('td').each(function () {
      wiki += '| ' + $(this).text() + ' ';
    });
    wiki += "\n";
  });
});
wiki += "|}"
$('#result').html(wiki);
</script>

2 예제2: colspan, rowspan 처리[ | ]

<style>
th, td, pre { border: 1px solid #000; }
</style>
<table id='mytable'>
  <tr><th colspan='2'>Num</th><th>-ary</th></tr>
  <tr><td>1</td><td rowspan='2'>One</td><td>unary</td></tr>
  <tr><td>2</td><td>binary</td></tr>
</table>
<hr>
<pre id='result'></pre>

<script src="//code.jquery.com/jquery.min.js"></script>
<script>
var wiki="{| class='wikitable'\n";
$('#mytable').each(function() {
  $(this).find('tr').each(function () {
    wiki += '|-\n';
    $(this).find('th,td').each(function () {
    	console.log($(this).prop("tagName"));
    	var sep = ( $(this).prop("tagName") == "TH" )? "!": "|";
      wiki += sep;
	  	if( $(this).attr('colspan') || $(this).attr('rowspan') ) {
      	 if( $(this).attr('colspan') ) wiki += " colspan=" + $(this).attr('colspan');
      	 if( $(this).attr('rowspan') ) wiki += " rowspan=" + $(this).attr('rowspan');
         wiki += "|";
      }
      wiki += " " + $(this).text() + "\n";
    });
  });
});
wiki += "|}";
$('#result').html(wiki);
</script>

3 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}