Jas*_*nis 4 jquery split css-selectors
我有一个和平的HTML看起来像这样:
<h3>PETIT DEJEUNER</h3>
<p>FRANS ONTBIJT</p>
<p>CROISSANT</p>
<p>CROISSANT</p>
<h3>AUTRE PETIT DEJEUNER</h3>
<p>FRANS ONTBIJT</p>
<p>CROISSANT</p>
<p>CROISSANT</p>
<h3>AND ONE MORE DEJEUNER</h3>
<p>FRANS ONTBIJT</p>
<p>CROISSANT</p>
<p>CROISSANT</p>
Run Code Online (Sandbox Code Playgroud)
当然内容各不相同.不幸的是我不控制html,它是从另一个来源传递的.我可以在每个h3分割内容,创建一个这样的集合:
menu = [
{
title: 'PETIT DEJEUNER',
contents: [<p contents>,<p contents>,<pcontents>]
},
{
title: 'AUTRE PETIT DEJEUNER',
contents: [<p contents>,<p contents>,<pcontents>]
},
]
Run Code Online (Sandbox Code Playgroud)
我正在使用jQuery.谢谢!
您可以组合nextUntil()和filter()来匹配<h3>元素之间的段落,并使用map()来构建数组:
var menu = $("h3").map(function() {
var $this = $(this);
return {
title: $this.text(),
contents: $this.nextUntil("h3").filter("p").map(function() {
return $(this).text();
}).get();
};
}).get();
Run Code Online (Sandbox Code Playgroud)