【问题标题】:Fill textarea with clicked button用单击的按钮填充文本区域
【发布时间】:2012-02-16 08:29:51
【问题描述】:

已解决

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>

现在我得到了我点击的所有文本区域...http://jsfiddle.net/ArtofLife/u9d9d/15/

我只想填充最后一个被点击的文本区域,而不是冒泡变量 pos..

【问题讨论】:

    标签: javascript jquery jquery-selectors jquery-events


    【解决方案1】:

    这是因为您在textarea click 处理程序中拥有.insertclick 处理程序。每当您单击textarea 时,都会附加一个新的处理程序,并且当您单击任何textarea 时,它会继续附加。把它移到外面就可以了。

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

    Demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-31
      • 1970-01-01
      • 2012-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多