使用Javascript书签按标题分块页面内容第2部分

问题描述

|| 我有一些@pimvdb帮助我处理的Java脚本,我想知道是否可以对其进行调整,以便将较小的标题ѭ0分组到下一个较高的ѭ0之中。 换句话说,从以下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>
    

解决方法

只为每个不同的标题分配类而不是使用: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\'>\") );
    });


};
    ,更改了我对第一部分的回答:
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]);
 }
    

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...