本文介绍了使用javascript将文本附加到textarea的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将文本列表附加到文本区域?
How can I append a list of text into a textarea?
<textarea id="alltext"></textarea> <ol> <li onclick="addText(Hello')">Hello</li> <li onclick="addText(World')">World</li> <li onclick="addText(Earthlings')">Earthlings</li> </ol> <script> var Alltext = ""; function addText(text) { Alltext += text } document.getElementById("alltext").value = Alltext; </script>由于列表实际上很长,因此效率很低.添加的文本恰好是我在HTML上看到的值,因此无需两次输入正确的代码?
This is quite inefficient as the list is actually very long. The text added is exactly the value I see on the HTML so there's no need to type it twice right?
还有更好的方法吗?
推荐答案通过将onclick分配给<ol>来使用事件委托.然后将event对象作为参数传递,并使用该对象从单击的元素中获取文本.
Use event delegation by assigning the onclick to the <ol>. Then pass the event object as the argument, and using that, grab the text from the clicked element.
function addText(event) { var targ = event.target || event.srcElement; document.getElementById("alltext").value += targ.textContent || targ.innerText; }
<textarea id="alltext"></textarea> <ol onclick="addText(event)"> <li>Hello</li> <li>World</li> <li>Earthlings</li> </ol>
请注意,这种传递event对象的方法在较旧的IE和W3兼容系统中都适用.
Note that this method of passing the event object works in older IE as well as W3 compliant systems.
更多推荐
使用javascript将文本附加到textarea
发布评论