実現したいこと
jQueryを使用して、表示した<section></section>を二つの<section></section>に分割したい
前提
DBから取得してきたデータを元に、グラフや表などを表示させるようなプログラムを作ったのですが、
印刷するときに中途半端なところで途切れてしまうのが嫌なので、途中で改ページを入れたいと思っています。
DBに格納されているデータを使って、一旦そのままのデータでHTMLを出力し、
<section></section>で区切って改ページのためのCSSを当てているのですが、 一部のデータでページをはみ出してしまうケースが発生したため、jQueryで<section></section>内部の要素の高さを読み込み、 一定値以上になったら</section><section>を挿入して強制的に改ページを入れようとしました。しかし、実際に動作させてみると</section><section>ではなく<section></section>が入ってしまうだけで、うまく改ページができません。
指定したHTMLをそのまま挿入させ、一つの<section></section>を二つに区切るには、どうすれば良いのでしょうか。
発生している問題・エラーメッセージ
エラーメッセージ
該当のソースコード
HTML(出力直後)
1<section class="print_page"> 2 <p class="print_header">ヘッダー</p> 3 <h1 class="content_block">見出し</h1> 4 <h2 class="content_block">小見出し</h2> 5 <div class="content_block"><canvas>chart.jsで出力したグラフ</canvas></div> 6 <table class="content_block">コメントの一覧1</table> 7 <table class="content_block">コメントの一覧2</table> 8 <table class="content_block">コメントの一覧3</table> 9 <table class="content_block">コメントの一覧4</table> 10 <table class="content_block">コメントの一覧5</table> 11 <p class="print_footer">フッター</p> 12</section>
javascript
1$(function() { 2 $('.print_page').each(function() { 3 var contents_height = 0; 4 $(this).children().each(function() { 5 var this_height = $(this).outerHeight(); 6 if (this_height + contents_height >= 900) { 7 $(this).after('<p class="print_footer">フッター</p></section><section class="print_page"><p class="print_header">ヘッダー</p>'); 8 contents_height = 0; 9 } else { 10 contents_height += this_height; 11 } 12 }); 13 }); 14});
HTML(期待する結果)
1<section class="print_page"> 2 <p class="print_header">ヘッダー</p> 3 <h1 class="content_block">見出し</h1> 4 <h2 class="content_block">小見出し</h2> 5 <div class="content_block"><canvas>chart.jsで出力したグラフ</canvas></div> 6 <table class="content_block">コメントの一覧1</table> 7 <table class="content_block">コメントの一覧2</table> 8 <table class="content_block">コメントの一覧3</table> 9 <p class="print_footer">フッター</p> 10</section> 11<section class="print_page"> 12 <p class="print_header">ヘッダー</p> 13 <table class="content_block">コメントの一覧4</table> 14 <table class="content_block">コメントの一覧5</table> 15 <p class="print_footer">フッター</p> 16</section>
HTML(実際の結果)
1<section class="print_page"> 2 <p class="print_header">ヘッダー</p> 3 <h1 class="content_block">見出し</h1> 4 <h2 class="content_block">小見出し</h2> 5 <div class="content_block"><canvas>chart.jsで出力したグラフ</canvas></div> 6 <table class="content_block">コメントの一覧1</table> 7 <table class="content_block">コメントの一覧2</table> 8 <table class="content_block">コメントの一覧3</table> 9 <p class="print_footer">フッター</p> 10 <section> 11 <p class="print_header">ヘッダー</p> 12 </section> 13 <table class="content_block">コメントの一覧4</table> 14 <table class="content_block">コメントの一覧5</table> 15 <p class="print_footer">フッター</p> 16</section>
試したこと
・HTMLを挿入する箇所をafter → appendにしてみる
→挿入される箇所が変わっただけで、期待した状態にはならない
補足情報(FW/ツールのバージョンなど)
・jQuery3.4.1
