我有以下代码,我需要创建一个嵌套数组,我将生成一个多级有序列表。
var htmlContent2 = '<div id="header"><p class="headpara">Header content</p><p class="one">Lorem ipsum dolor sit amet, consectetur:</p><p class="two">Perferendis iure doloremque iusto adipisci facilis.</p><p class="two">Asperiores impedit officiis cumque molestias at rerum consequuntur!</p><p class="one">More dummy text.</p> <p class="two">Additional dummy text: </p> <p class="three">Asperiores impedit officiis.</p> <p class="three">Lolestiae asperiores ad repellat est obcaecati.</p> <p class="two">Lorem ipsum dolor sit amet.</p> <p class="notelem">Dignissimos maiores facere consequuntur quod.</p> <p class="one">Ea excepturi aperiam.</p></div>';
var $ = cheerio.load(htmlContent2);
var allList = [];
var manipulatedContent = $('#header').each(function (i, elem) {
var level1 = [],
level2 = [],
level3 = [],
level4 = [],
item1 = $('.one').html(),
item2 = $('.two').html(),
item3 = $('.three').html(),
item4 = $('.notelem').html();
level1[i] = item1;
level2[i] = item2;
level3[i] = item3;
level4[i] = item4;
allList.push(item1, [item2, [item3, item4]]);
});
console.dir(allList);
使用我当前的代码,我只能生成以下数组:
[ 'Lorem ipsum dolor sit amet, consectetur:',
[ 'Perferendis iure doloremque iusto adipisci facilis.',
[ 'Asperiores impedit officiis.',
'Dignissimos maiores facere consequuntur quod.']]]
但是想要的结果数组:
['Lorem ipsum dolor sit amet, consectetur:',
['Perferendis iure doloremque iusto adipisci facilis.',
['Asperiores impedit officiis.',
['Dignissimos maiores facere consequuntur quod.']]]];
如何使用JavaScript或任何更好的cheerio.js方法实现这一目标?
我的目标是从格式不佳的html创建一个嵌套的有序列表,如示例内容(htmlContent2)所示。
非常感谢您的帮助。
答案 0 :(得分:0)
正如@Chris G评论的那样:
//var htmlContent2 = '';
//var $ = cheerio.load(htmlContent2);
var allList = [];
var manipulatedContent = $('#header').each(function (i, elem) {
var level1 = [],
level2 = [],
level3 = [],
level4 = [],
item1 = $('.one').html(),
item2 = $('.two').html(),
item3 = $('.three').html(),
item4 = $('.notelem').html();
level1[i] = item1;
level2[i] = item2;
level3[i] = item3;
level4[i] = item4;
allList.push(item1, [item2, [item3, [item4]]]);
});
console.dir(allList);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="header"><p class="headpara">Header content</p><p class="one">Lorem ipsum dolor sit amet, consectetur:</p><p class="two">Perferendis iure doloremque iusto adipisci facilis.</p><p class="two">Asperiores impedit officiis cumque molestias at rerum consequuntur!</p><p class="one">More dummy text.</p> <p class="two">Additional dummy text: </p> <p class="three">Asperiores impedit officiis.</p> <p class="three">Lolestiae asperiores ad repellat est obcaecati.</p> <p class="two">Lorem ipsum dolor sit amet.</p> <p class="notelem">Dignissimos maiores facere consequuntur quod.</p> <p class="one">Ea excepturi aperiam.</p></div>