【发布时间】:2016-12-09 11:57:19
【问题描述】:
所以我有12个段落,这些段落被三个p标签分成四组。我需要做的是每三段获取10个符号(包括空格共30个符号)并将其联系人添加到h1标签,需要做4次,因为有3组12个段落。
<div id="pastraipos">
<h1></h1>
<p>is simply dummy text of the printing and typesetting industry. </p>
<p>it is a long established fact that a reader will be distracted.</p>
<p>There are many variations of passages of Lorem Ipsum available.</p>
<h1></h1>
<p>is simply dummy text of the printing and typesetting industry. </p>
<p>is simply dummy text of the printing and typesetting industry. </p>
<p>is simply dummy text of the printing and typesetting industry. </p>
<h1></h1>
<p>is simply dummy text of the printing and typesetting industry. </p>
<p>is simply dummy text of the printing and typesetting industry. </p>
<p>is simply dummy text of the printing and typesetting industry. </p>
<h1></h1>
<p>is simply dummy text of the printing and typesetting industry. </p>
<p>is simply dummy text of the printing and typesetting industry. </p>
<p>is simply dummy text of the printing and typesetting industry. </p>
</div>
html代码中没有h1标签,我只是给你写的,所以它可能更清楚,因为我很难解释它。 所以有代码,我每3段添加h1标签:-
var parent = document.getElementById("pastraipos");
var children = parent.childElementCount;
console.log(children);
for (var i=0; i<=children; i=i+4){
var h = document.createElement("H1");
var t = document.createTextNode("Hello World"); //there should be no hello world it should contain 30 symbols from three paragraphs (10 from each including space)
h.appendChild(t);
parent.insertBefore(h, parent.children[i]);
}
这是我编写的代码,用于获取每三个段落的 10 个符号
for (j=0; j<3; j++){
var str = document.getElementsByTagName("p")[j].textContent;
console.log(str);
var res = str.substring(0, 10);
console.log(res);
var labas = labas + res;
}
var s = document.createElement("H1");
var t = document.createTextNode(labas);
s.appendChild(t);
parent.appendChild(s);
这应该出现在第一个 h1
<h1>is simply it is a lot here are </h1>(30 elements total)
所以我有代码,每 3 段添加 h1 标记,我有一些代码,从 3 段中收集 10 个符号并将文本添加到 h1,遗憾的是它只适用于第一个 h1,因为我需要以某种方式组合这两个循环?但我不知道怎么做。
【问题讨论】:
-
为什么不使用带有 nth-of-type 和 ::after 的 css?
-
只能用js和dom做,可惜没有css
标签: javascript html for-loop dom