簡體   English   中英

將文字插入<textarea>

[英]insert text into <textarea>

我試圖在單擊另一個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 ,則應將值發送到服務器,並在服務器端填寫textarea。 如果這不必要地復雜或不可行,則可以通過多種不同的方式傳遞文本,最常見的方式是:

  • 在網址html2.html?text="my text"
  • 在Cookie中(大多數情況下不建議使用)

如果通過URL進行操作,只需從html2.html上的JavaScript中的URL中提取文本html2.html

運行“ window.location”后,新頁面將開始加載,腳本將停止執行。

此外,您無法在以后的頁面上修改元素。

最好的方法是加載html2.html#someTextHere ,然后在html2.html文本從哈希值復制到textarea中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM