将文本插入<text区域>

insert text into <textarea>

本文关键字:text 区域 gt lt 文本 插入      更新时间:2023-12-26

当单击其他html页面中的链接时,我正试图将文件中的一些文本插入到html文件中的<textarea></textarea>中。

html1.html:

<a href="#" id="link">click to add text</a>

html2.html:

<form action="...">
   <textarea id="txt"></textarea>
</form> 

js:

$(".link").click(function(){
   window.location = "./html2.html";
   var text = $("#some_id").text();
   $("#txt").val(text)
});

一旦迁移到新页面,任何进一步的JS执行都将丢失。您必须执行这样的操作,将文本传递到查询字符串变量中的新页面:

$(".link").click(function(){
   var encodedText = encodeURIComponent($("#some_id").text());
   window.location = "./html2.html?txt=" + encodedText;
});

在你的html2.html页面上有这样的代码:

var capturedText = window.location.search.match(/('?|&)txt=(.*?)(&|$)/);
capturedText = capturedText ? decodeURIComponent(capturedText[2]) : '';
$("#txt").val(capturedText);

如果some_idhtml2.html中,那么很容易:让html2.html中的JavaScript填充文本

$("#txt").val($("#some_id").text());

如果some_idhtml1.html中,则应将值发送到服务器,并填写服务器端的文本区域。如果这是不必要的复杂或不可行的,你可以通过多种不同的方式传递文本,最常见的是:

  • 在URL html2.html?text="my text"
  • 在cookie中(大多数情况下不推荐)

如果您通过URL进行操作,只需从html2.html上JavaScript中的URL中提取文本即可。

运行"window.location"后,新页面将开始加载,脚本将停止执行。

此外,您不能修改未来页面上的元素。

最好的方法是加载html2.html#someTextHere,然后在html2.html上将文本从散列复制到文本区域。