Home > Article > Backend Development > 如何在textarea输入的内容,每段都被<p></p>包裹起来?
例如输入的时候:
我是一个粉刷匠
大家好
啦啦啦
输入完后提交后转成:
我是一个粉刷匠
大家好
啦啦啦
<code class="language-js"><span class="kd">var</span> <span class="nx">val</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nx">getElementsByTagName</span><span class="p">(</span><span class="s1">'textarea'</span><span class="p">)[</span><span class="mi">0</span><span class="p">].</span><span class="nx">value</span><span class="p">;</span>
<span class="nx">val</span> <span class="o">=</span> <span class="nx">val</span><span class="p">.</span><span class="nx">replace</span><span class="p">(</span><span class="s2">"\n"</span><span class="p">,</span><span class="s2">"<p>"</p></span><span class="p">);</span>
<span class="nx">val</span> <span class="o">=</span> <span class="s2">"<p>"</p></span> <span class="o">+</span> <span class="nx">val</span> <span class="o">+</span> <span class="s2">""</span><span class="p">;</span>
</code>
听上去挺简单,事实上要跨浏览器的话挺麻烦的。主要是换行可能是br, p, div