使用单击的按钮代码填充textarea

时间:2012-01-22 19:38:48

标签: javascript jquery javascript-events jquery-selectors

解决

http://jsfiddle.net/ArtofLife/u9d9d/

我有多个TEXTAREA和BUTTON出来..为了在textarea中插入字符串,我使用了jQuery插件(insertAtCaret)。如何只填写最后点击的TEXTAREA文本......?

<textarea name="answer_text[0]" cols="50" rows="3" style="width: 99%;">
    AAA
</textarea>

<textarea name="answer_text[1]" cols="50" rows="3" style="width: 99%;">
    BBB
</textarea>

<textarea name="answer_text[2]" cols="50" rows="3" style="width: 99%;">
    CCC
</textarea>

<textarea name="answer_text[3]" cols="50" rows="3" style="width: 99%;">
    Here should be:
    &lt;button class=insert name=insert&gt;Insert&lt;/button&gt; 
</textarea>

<button class=insert name=insert>Insert</button>

<script type="text/javascript">
jQuery.fn.extend({
insertAtCaret: function(myValue) {
    return this.each(function(i) {
        if (document.selection) {
            //For browsers like Internet Explorer
            this.focus();
            sel = document.selection.createRange();
            sel.text = myValue;
            this.focus();
        }
        else if (this.selectionStart || this.selectionStart == '0') {
            //For browsers like Firefox and Webkit based
            var startPos = this.selectionStart;
            var endPos = this.selectionEnd;
            var scrollTop = this.scrollTop;
            this.value = this.value.substring(0, startPos) + myValue + this.value.substring(endPos, this.value.length);
            this.focus();
            this.selectionStart = startPos + myValue.length;
            this.selectionEnd = startPos + myValue.length;
            this.scrollTop = scrollTop;
        } else {
            this.value += myValue;
            this.focus();
        }
    });
}
});

var pos = 0;
$('textarea').click(function() {
//Get the name of this clicked item
var pos = $(this).attr("name");
$('.insert').click(function() {
    $('textarea[name^="' + pos + '"]').insertAtCaret('Actual button code');
});
return false;
});
</script>

现在我收到了我点击的所有textareas ... http://jsfiddle.net/ArtofLife/u9d9d/15/

我想只填充点击的最后一个textarea,而不是冒泡变量pos ..

1 个答案:

答案 0 :(得分:0)

这是因为.insert click处理程序中有textarea的{​​{1}}处理程序。每当您点击click时,都会附加一个新的处理程序,当您点击任何textarea时,它会一直附着。将它移到外面它会正常工作。

textarea

<强> Demo