2009-08-07 49 views
6

我知道如何填充一個textarea,但如何填充它,以便它保持換行符?你如何用jquery和linebreaks填充textarea?

e.g

HTML

<div id="previous_purchases">blah blah blah<br />blah blah</div> 

jQuery的

$('#previous_purchases').click(function(){ 

     var what = $(this).text(); 

     $('#purchased').text(what); 


}); 

所有嗒嗒只是搖滾起來textarea的上一行。有任何想法嗎?

編輯:我一直在嘗試使用html()而不是文本,但它會產生相同的結果。我會想象通過使用html()我會最終得到'
'的textarea,但事實並非如此......它只是在一條線上。

即使使用這樣的代碼:

$('#previous_purchases').click(function(){ 

     var what = $(this).html(); 

     $('#purchased').html(what); 


}); 

回答

5

嘗試這樣做:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
    <html xmlns="http://www.w3.org/1999/xhtml" > 
    <head> 
     <title></title> 
     <script src="scripts/jquery-1.3.2.min.js" type="text/javascript"></script> 
     <script type="text/javascript"> 
      $(document).ready(
       function() { 
       $('#previous_purchases').click(function() { 
       var what = $(this).html().replace(/<br>/, '\n'); 
       $('#purchased').html(what); 
      }); 
     }); 
     </script> 
    </head> 
    <body> 
    <div id="previous_purchases">blah blah blah<br />blah blah</div> 
    <textarea id="purchased" cols="25" rows="10"></textarea> 
    </body> 
    </html> 

Attributes/html

+0

代替
對不起,我應該澄清一下,html()是我的第一次嘗試。 – willdanceforfun 2009-08-07 03:17:53

+0

我本該更清楚一點。您需要將html拉入「what」,並將其添加到#exchased使用html()。我用一個完整的HTML例子來編輯我的評論。 – 2009-08-07 03:52:51

+0

抱歉,如果第一句關於聲音的句子突然發生,那不是意味着什麼。我希望這對你有用! – 2009-08-07 03:55:11

2

而不是調用的文本()的函數,你可以使用HTML()和路徑格式化的文本它。

$('#previous_purchases').click(function(){ 

       var what = $(this).text(); 

       $('#purchased').html(what); 


}); 
+0

這似乎不適用於我:|我的意思是它應該...我的頭說它應該... – willdanceforfun 2009-08-07 03:20:09

2

text()自動去掉html。所以基本上你會想用html()代替文本,並用\ n

+0

你能解釋更多關於插入\ n?多數民衆贊成在textarea解釋新線......但如何把它們放入? – willdanceforfun 2009-08-07 04:50:56