使用javascript将文本附加到textarea

编程入门 行业动态 更新时间:2024-10-06 14:36:08
本文介绍了使用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

本文发布于:2023-11-02 06:24:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1551613.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文本   javascript   textarea

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!