2011-02-28 87 views
0

我有一個textarea和一個包含幾個變量的列表。我需要能夠點擊一個變量並將其放入文本區域。用jQuery將文本插入到textarea中

<div id="var1" class="insert">Name</div> 
<div id="var2" class="insert">Street address</div> 

<textarea id="targetText">some text already here</textarea> 

插入後,我需要它看起來像:

<textarea id="targetText">some text already here {Street address}</textarea> 

我在考慮使用點擊功能:

$(".insert").click(function() { 
     // some magic to add to textarea 
}); 

回答

3

試試這個:

$(".insert").click(function() { 
    var insertText = $(this).text(); 
     $('#targetText').append(" "+insertText); 
}); 

演示:http://jsfiddle.net/Wkz6U/

+0

完美!並始終爲jsfiddle鏈接+1。 – santa 2011-02-28 19:02:58

+0

@santa歡迎您:) – Sotiris 2011-03-01 22:13:41

2
$("#targetText").val($("#targetText").val() + "{" + $(this).text() + "}"); 

感覺神奇。

5

如果要插入光標處的變量,你需要使用selectionStart如下:

$('.insert').click(function(e){ 
    var tav = $('#targetText').val(), 
     strPos = $('#targetText')[0].selectionStart; 
     front = (tav).substring(0,strPos), 
     back = (tav).substring(strPos,tav.length); 

    $('#targetText').val(front + '{' + $(this).text() + '}' + back); 
}); 

見琴:http://jsfiddle.net/rKmVL/1/

注:這可能是行不通的原樣在IE中。

相關問題