javascript 如何在div内容上添加段落

flvlnr44  于 5个月前  发布在  Java
关注(0)|答案(8)|浏览(69)

如何在div容器中添加多个段落标签,在顶部新建标签。

<div id="pcontainer">
  <p>recently added on top every time on click event recently added paragarph on top</p>
  <p>added before recent</p>
</div>

字符串
我使用追加,但每次我点击按钮,它添加到底部,我需要它添加在所有段落的顶部,请帮助。

b1uwtaje

b1uwtaje1#

您可以使用prepend将段落添加到容器的顶部:

// HTML: <div><p>Lorem ipsum</p></div>
$('div').prepend('<p>Bla bla bla');

字符串

更新:关于您对如何淡入段落的评论-使用fadeIn:

$("#pcontainer").prepend($('<p>This paragraph was added by jQuery.</p>').fadeIn('slow'));


一个工作演示:http://jsbin.com/uneso

h9vpoimq

h9vpoimq2#

一种不使用jQuery的更优雅的方式:

var container = document.getElementById('pcontainer');
container.insertBefore(document.createElement("p"), container.firstChild);

字符串
这假设容器btw中已经有一个元素。

qnakjoqk

qnakjoqk3#

非jQuery用户的示例:

document.getElementById('pcontainer').innerHTML = '<p>new paragraph</p>' + document.getElementById('pcontainer').innerHTML;

字符串
也许不是那么短和漂亮:)

aiqt4smr

aiqt4smr4#

尝试使用prepend而不是append。

oyxsuwqo

oyxsuwqo5#

下面是一个没有jQuery的方法:

function prependParagraphs()
{
     var choosenDiv = document.getElementById("pcontainer");
     for(var i=0; i<5; i++)
     {
         var newP = document.createElement("p");
         var text = document.createTextNode("new paragraph number: " + i);
         newP.appendChild(text);
         choosenDiv.insertBefore(newP, choosenDiv.firstChild);
     }
}

字符串

okxuctiv

okxuctiv6#

具体到您的HTML,它将是:

$("#pcontainer").prepend('<p>here's a new paragraph!</p>');

字符串

wixjitnu

wixjitnu7#

你可以使用一个小技巧,例如,首先将新的html存储在一个变量中,并将它与旧的内容一起附加到容器中。

const container = document.getElementById("pcontainer")
container.innerHTML = `<p>new para you want to add</p> ${container.innerHTML}`

字符串

brtdzjyr

brtdzjyr8#

没有jquery的更新解决方案是使用prepend()方法。“

function add() {
  let p = document.createElement('p')
  p.innerText = 'added before'
  document.getElementById('pcontainer').prepend(p)
}

button = document.getElementById('add')
button.addEventListener('click', add)

个字符

相关问题