我有@pimvdb帮我here的一些javascript,我想知道它是否可以进行调整,以便在下一个更高的位置对较小的标题div
进行分组div
。
换句话说,从这个HTML开始:
<p>Some paragraph</p>
<h1>Heading 1</h1>
<p>Some paragraph</p>
<p>Some paragraph</p>
<h2>Heading 2</h2>
<p>Some paragraph</p>
<p>Some paragraph</p>
<h3>Heading 3</h3>
<p>Some paragraph</p>
<p>Some paragraph</p>
<h1>Heading 1</h1>
<p>Some paragraph</p>
<p>Some paragraph</p>
<h2>Heading 2</h2>
<p>Some paragraph</p>
<p>Some paragraph</p>
<h3>Heading 3</h3>
<p>Some paragraph</p>
<p>Some paragraph</p>
...
...然后使用javascript(通过书签,因为它必须在客户端完成)最终得到这个:
<div class="one">
<h1>Heading 1</h1>
<p>paragraph</p>
<div class="two">
<h2>Heading 2</h2>
<p>paragraph</p>
<div class="three">
<h3>Heading 3</h3>
<p>paragraph</p>
</div>
<div class="three">
<h3>Heading 3</h3>
<p>paragraph</p>
</div>
</div>
</div>
<div class="one">
<h1>Heading 1</h1>
<p>paragraph</p>
<div class="two">
<h2>Heading 2</h2>
<p>paragraph</p>
<div class="three">
<h3>Heading 3</h3>
<p>paragraph</p>
</div>
</div>
</div>
答案 0 :(得分:0)
如何将类分配给每个不同的头而不是使用:header,单独使用每个元素类型并从最高到最低工作。
function a() {
$('h3').each(function() {
$(this)
.add($(this).nextUntil( $("h3")) ).wrapAll( $("<div class='three'>") );
});
$('h2').each(function() {
$(this)
.add($(this).nextUntil( $("h2")) ).wrapAll( $("<div class='two'>") );
});
$('h1').each(function() {
$(this)
.add($(this).nextUntil( $("h1")) ).wrapAll( $("<div class='one'>") );
});
};
答案 1 :(得分:0)
改变了我对第一部分的回答:
var parent = document.body, i;
var tmpArray = [];
for (i=0; i<parent.childNodes.length; i++)
tmpArray.push(parent.childNodes[i]);
var headerArray = [];
var classNames = [null, "one", "two", "three", "four", "five"]
var newArray = [], currElem = null;
for (i=0; i<tmpArray.length; i++) {
var elem = tmpArray[i];
var tagData = null;
var which;
if (elem.tagName &&
elem.tagName.charAt(0) == 'H' &&
(which = parseInt(elem.tagName.charAt(1))) > 0) {
currElem = document.createElement("div");
currElem.className = classNames[which];
currElem.appendChild (elem);
headerArray[which] = currElem;
if (which > 1)
headerArray[which-1].appendChild(currElem);
else
newArray.push(currElem);
}
else {
if (currElem)
currElem.appendChild (elem);
else
newArray.push(elem);
}
}
parent.innerHTML = '';
for (i=0; i<newArray.length; i++) {
parent.appendChild (newArray[i]);
}