简体   繁体   English

如何使用textarea更改段落

[英]how to change paragraph with textarea

So I'm newbie in web development and I wanted to create paragraph that could change its textContent with textarea.所以我是 Web 开发的新手,我想创建可以使用 textarea 更改其 textContent 的段落。 I mean: if I would write 'Hello World!'我的意思是:如果我会写“Hello World!” in textarea, I wanted the content of paragraph change into text, that is written in the textbox.在textarea中,我希望段落的内容变成文本,写在文本框中。 with JavaScript of course.当然使用 JavaScript。 but I have no idea how to do it.但我不知道该怎么做。 I had some tries but they all failed.我有一些尝试,但都失败了。 Here is my HTML, I need JavaScript Tutor...这是我的 HTML,我需要 JavaScript Tutor...

<p class="test-text"></p>

<textarea class="tarea" name="textarea" cols="30" rows="10"></textarea>

and variables that I created:和我创建的变量:

var paragraph = document.querySelector('.test-text');
var tarea = document.querySelector('.tarea');

Can u guys help me :D你们能帮我吗:D

I would give both an id, so you can get them easier.我会给两者一个 id,这样你就可以更容易地获得它们。 Using the classname might work, but if you want to make another element of that class it would not work.使用类名可能会起作用,但如果您想创建该类的另一个元素,它将不起作用。 And if you are only using the classes to identify the elements, you should use id anyway, since this is what they are made for.如果您只使用类来标识元素,则无论如何都应该使用 id,因为这是它们的用途。 It would then look like this:然后它看起来像这样:

<p class="test-text" id="myParagraph"></p>

<textarea class="tarea" id="myTextarea" name="textarea" cols="30" rows="10"></textarea>

Then you can simply set the textArea with this:然后你可以简单地设置 textArea 与这个:

var text = document.getElementById("myParagraph").textContent;
document.getElementById('myTextarea').value = text;

Pls note that textContent only works as exspected if you have no other elements inside your paragraph tag.请注意,如果您的段落标记中没有其他元素,则 textContent 仅按预期工作。 Otherwise the textContent of the underlying elements woould be included in the textContent of the paragraph element.否则,底层元素的 textContent 将包含在段落元素的 textContent 中。

First you need to grab the elements:首先,您需要获取元素:

HTML:
<p id="text" class="test-text"></p>

<textarea id="text-area" class="tarea" name="textarea" cols="30" rows="10"></textarea>

JS:
var paragraph = document.querySelector('#text');
var tarea = document.querySelector('#text-area');

I added ids for the elements我为元素添加了 id

Then you need to add an event listener to the textarea:然后你需要在textarea中添加一个事件监听器:

tarea.addEventListener('input', updateValue);

Now you can create a function to update the paragraph:现在您可以创建一个函数来更新段落:

function updateValue(e) {
  paragraph.textContent = e.target.value;
}

NOTE that the updateValue will be executed when you will type something in the textarea请注意,当您在 textarea 中键入内容时将执行 updateValue

You can check this for more information您可以查看以获取更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM