简体   繁体   English

如何从javascript向HTML页面添加文本?

[英]How to add a text to HTML page from javascript?

I have a textarea in HTML page ( page.html ) and it has JavaScript in it, so what I want is, through JavaScript I could add the text in another HTML page ( page2.html ) written in the textarea of page1.html . 我有一个textarea在HTML页面( page.html ),它有它的JavaScript,所以我要的是,通过JavaScript我可以在另一个HTML页面(添加文本page2.html )写在textareapage1.html How can it be done? 如何做呢?

To do this, you must first create a new text node. 为此,您必须首先创建一个新的文本节点。 This statement creates a new text node with the text "this is a test": 该语句使用文本“这是一个测试”创建一个新的文本节点:

var node=document.createTextNode("this is a test");

Next, you can add this node to the document. 接下来,您可以将此节点添加到文档中。 To do this, you use the appendChild method. 为此,您可以使用appendChild方法。 The text can be added to any element that can contain text, but we will use a paragraph. 可以将文本添加到可以包含文本的任何元素中,但是我们将使用一个段落。 The following statement adds the text node defined above to the paragraph with the identifier p1 : 以下语句将上面定义的文本节点添加到带有标识符p1的段落中:

document.getElementById("p1").appendChild(node);

You will need some kind of back-end. 您将需要某种后端。 page.html sends ajax request to backend with updated value, page2.html sends ajax request to backend to get that value. page.html将ajax请求发送到具有更新后值的后端, page2.html将ajax请求发送到后端以获取该值。 If you don't know any back-end language (node.js, php for example), it will be hard to achieve this. 如果您不懂任何后端语言(例如,node.js,php),将很难实现。

Another case if for example page2.html is "iframed" into page.html , then you can access directly with Javascript. 另一种情况是,例如将page2.htmlpage2.html ”到page.html ,则可以直接使用Javascript访问。

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

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