2 回答
TA贡献1829条经验 获得超13个赞
这并不完美,需要进一步开发以解释具有不同标题变化的部分,但应该为您提供一个良好的起点
使用nextUntil()它包装h1一个部分中的组,然后循环遍历这些部分以使用它们的索引作为主要编号,然后循环h2获取次要编号等
// wrap all h1 in a section
$('h1').each(function() {
$(this).nextUntil('h1').add(this).wrapAll('<section>');
});
// loop over sections after first one
$('section:gt(0)').each(function(i) {
const num = i + 1, $sect = $(this);
$sect.find('h1').prepend(`${num} `);
$sect.find('h2').each(function(i) {
const subnum = i + 1;
$(this).text(function(_, txt) {
return `${num}.${subnum} ${txt}`
});
$(this).nextUntil('h2', 'h3').text(function(i, txt) {
return `${num}.${subnum}.${i+1} ${txt}`
});
});
});
section { border: 2px solid #ccc}
h1 {color: red}
h2 {color: blue}
h3 {color: green}
h1,h2,h3,h4,p{margin:0}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<article class="markdown-section" id="main">
<h1 id="about-this-document">About this document</h1>
<p>This is the online documentation of the <strong>Company Procedures</strong>.</p>
<h1 id="everyone">Everyone</h1>
<h2 id="logging-into-your-computer">Logging into your computer</h2>
<p>These are the instructions on how to log into your computer.</p>
<ol>
<li>Step one</li>
<li>Step two</li>
</ol>
<h2 id="programmes-on-taskbar">Programmes on taskbar</h2>
<h3 id="microsoft-word">Microsoft Word</h3>
<p>This is a word processor</p>
<h3 id="mail">Mail</h3>
<p>This is for your emails</p>
<h3 id="document-management">Document management</h3>
<h4 id="windows-explorer">Windows Explorer</h4>
<h4 id="xyplorer">XYPlorer</h4>
<h1 id="special-areas">Special areas</h1>
<h3 id="on-the-road">On the road</h3>
<h3 id="remote">Remote</h3>
</article>
TA贡献1784条经验 获得超7个赞
我刚刚.ol()为jQuery. 它创建一个有序列表并返回new具有方法的构造函数的实例.li()。该.li()方法返回对有序列表的引用。列出来!
function Ol(j){
const ol = $('<ol></ol>');
j.append(ol);
this.li = (title, noIncrement = false)=>{
let n = noIncrement ? '' : ' '+(ol.children().length+1);
let li = $('<li>'+title+n+'</li>');
ol.append(li);
return li;
}
}
$(function(){
$.fn.extend({
ol:function(){
return new Ol(this);
}
});
const test = $('#test'), titles = test.ol(), title1 = titles.li('Title'), sections = title1.ol();
for(let i=0,l=10; i<l; i++){
for(let n=0,chapters=sections.li('Chapter').ol(),q=4; n<q; n++){
for(let z=0,subs=chapters.li('Section').ol(),c=3; z<c; z++){
subs.li('sub-section').ol().li('content would go here', true);
}
}
}
const title2 = titles.li('Title').ol(), chapter1 = title2.li('Chapter').ol();
const chapter2 = title2.li('Chapter').ol(), chap1Sec1 = chapter1.li('Section').ol();
const chap2Sec1 = chapter2.li('Section').ol();
chap2Sec1.li('sub-section'); chap2Sec1.li('sub-section');
chap1Sec1.li('sub-section').ol().li('This is how you might use outside a loop', true);
});
*{
margin:0; padding:0;
}
ol{
list-style:none;
}
ol li{
margin-left:10px;
}
#test>ol>li{
margin-left:0;
}
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<div id='test'></div>
添加回答
举报