これを正しく読んでいる場合、2 つの div を含むアコーディオンの ID を持つ div があります。これら 2 つの div にはそれぞれ、ヘッダー タグと段落タグがあります。両方のヘッダー タグと両方の段落タグにコピーが含まれています。
多くの要素がその場で作成されているため、これを行うための非常にきちんとした方法は考えられません。createElement() でオフ DOM のものをすべて作成し、appendChild() で配置してから、ドキュメント フラグメントを介してすべてをロードすることは、パフォーマンスの観点から大幅に優れているため、良い方法だと思います。ポール・アイリッシュは、ここでこれらすべてについて詳しく説明しています。
$(function(){
// on the page already...just targeting it with a variable
var onPageEl = document.getElementById('list');
// created off-DOM...we'll load our stuff here before loading it onto the page
var frag = document.createDocumentFragment();
// create elements
var accordion = document.createElement('div');
var div1 = document.createElement('div');
var header1 = document.createElement('h3');
var somePara1 = document.createElement('p');
var div2 = document.createElement('div');
var header2 = document.createElement('h3');
var somePara2 = document.createElement('p');
// use jQuery to give our containing element an ID of 'accordion'
$(accordion).attr('id', 'accordion');
// arrange the first bulk of div code
accordion.appendChild(div1);
div1.appendChild(header1);
div1.appendChild(somePara1);
header1.innerHTML = "section1";
somePara1.innerHTML = "text1";
// arrange the second bulk of div code
accordion.appendChild(div2);
div2.appendChild(header2);
div2.appendChild(somePara2);
header2.innerHTML = "section2";
somePara2.innerHTML = "text2";
// Load both bulks of content into the document fragment
frag.appendChild(div1);
frag.appendChild(div2);
// Load the document fragment onto 'list' which is already on the page
onPageEl.appendChild(frag);
});
2 回作成されるものがあるため、関数を使用して作成することはできますが、パフォーマンスの問題が発生する可能性があります。
ちょうど私の 0.02 ドル...