2012-07-20 68 views
1

我试图在文件中插入一些文本到<textarea></textarea>在HTML文件中,当你点击一个不同的HTML页面中的链接。插入文本到<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) 
}); 
+0

在html1或html2中有'some_id'吗? – tskuzzy 2012-07-20 20:49:12

+1

window.location =“./html2.html”;会立即加载一个新页面,覆盖当前页面。因此脚本的其余部分将不会运行。 – 2012-07-20 20:50:34

+0

这里你最终的目标是什么?也许你没有看到它的工作,因为它真的让你到html2.html? – Zlatev 2012-07-20 20:51:16

回答

5

一旦你迁移到新页面,任何进一步的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); 
0

如果some_idhtml2.html,那么它很简单:有JavaScript的在HTML2 .html填入文字

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

如果some_idhtml1.html中,您应该将值发送到服务器并在服务器端填写textarea。在这过于复杂或不可行的情况下,你可以通过文字在许多不同的方式,最常见的是:

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

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

0

一旦你运行“window.location”,新页面将开始加载,脚本将停止执行。

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

你最好的办法是加载html2.html#someTextHere,并在html2.html把文本从散列复制到textarea中。