我的代碼如下追加一個HTML元素到當前元素以JavaScript
function addElem(){
var mElem = document.querySelector('.post_description')
var hElems = document.getElementsByTagName('H3');
var $index=1;
var node = document.createElement("a");
for(var i=0;i<hElems.length;i++){
//console.log(hElems[i].innerHTML);
var textnode = document.createTextNode(hElems[i].innerHTML);
var cloneElem = node.cloneNode(true);
cloneElem.appendChild(textnode);
mElem.appendChild(cloneElem);
mElem.appendChild($index++);
}
};
addElem()
.post_description{
height: 150px;
width:150px;
background-color:green;
position:absolute;
right:0;
top:0;
}
.post_description a{
display:block;
}
<div class="mg_post_description">
<div class="main_body">
<h3>Testing one</h3>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. ng essentially unchanged</p>
<h3>Testing two</h3>
<p>Lorem Ipsum is simply Lorem including versions of Lorem Ipsum.</p>
<h3>Testing three</h3>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem of Lorem Ipsum.</p>
</div>
</div>
<div class="post_description"></div>
這裏,我已經提取從內容H3標記給出,並且在「post_description」附加到創建的標籤DIV。我想在迭代中的標籤前添加一個數字計數器。意思是,第一個標籤會有數字1,然後打開。
我試圖使用$ index = 1,然後試圖追加$ index ++。
不過,我想在a或p標籤內添加索引號。如何才能做到這一點。
期待
感謝
傑夫
謝謝你的回答。 – jeff