Jquery将事件绑定到页面上的多个Textarea实例

时间:2016-05-04 23:15:38

标签: javascript jquery html binding textarea

我的脚本完全按照我需要的方式工作,刚才,我无法在页面上复制它 - jquery采用textarea框并根据按下的按钮编辑它们,但我需要每个textarea框都有它是自己的一组按钮。这是我的代码:

HTML CODE:

 <textarea style="width:500px; height: 150px;" id="text">This is some text</textarea>
<br />
<input type="button" value="Click Me" id="button" />
<input type="button" value="Click Me 2" id="button2" />

<br /><br />

<textarea style="width:500px; height: 150px;" id="text">This is some text</textarea>
<br />
<input type="button" value="Click Me" id="button" />
<input type="button" value="Click Me 2" id="button2" />

JAVASCRIPT:

function insertText(text) {
    var $textbox = $("#text");
    var textStr  = $textbox.text();
    var startPos = $textbox[0].selectionStart;
    var endPos   = $textbox[0].selectionEnd;

    // If set to true, the selection will NOT be replaced.
    // Instead, the text will be inserted before the first highlighted character.
    if (false)
    {
        endPost = startPos;
    }

    var beforeStr = textStr.substr(0, startPos);
    var afterStr  = textStr.substr(endPos, textStr.length);

    textStr = beforeStr + text + afterStr;
    $textbox.text(textStr);
    return textStr;
}

$(function () {
    $('#button').on('click', function () {
        insertText("\n\nafter clicking");    
    });
    $('#button2').on('click', function () {
        insertText("\n\nafter clicking 2");    
    });
});

JS小提琴: https://jsfiddle.net/0hmdu0ox/

1 个答案:

答案 0 :(得分:0)

您可以尝试以下版本:

<textarea style="width:500px; height: 150px;" id="txt1">This is some text</textarea>
<br />
<input type="button" value="Click Me" onclick="insertText('\n message1', 'txt1');" />
<input type="button" value="Click Me 2" onclick="insertText('\n message2', 'txt1');" />

<br /><br />

<textarea style="width:500px; height: 150px;" id="txt2"> This is some text</textarea>
<br />
<input type="button" value="Click Me"  onclick="insertText('\n message1', 'txt2');" />
<input type="button" value="Click Me 2" onclick="insertText('\n message2', 'txt2');" />

仅使用此功能:

function insertText(mess, txtA) {
    var textbox = $('#'+txtA);

    var textStr  = textbox.text();
    var startPos = textbox[0].selectionStart;
    var endPos   = textbox[0].selectionEnd;

    if (false) {
        endPost = startPos;
    }

    var beforeStr = textStr.substr(0, startPos);
    var afterStr  = textStr.substr(endPos, textStr.length);

    textStr = beforeStr + mess + afterStr;
    textbox.text(textStr);
    return textStr;
}


优化目标:

如果您可以在 insertText 函数中获得最接近的textarea,这将很棒......那么您不需要textarea的id,而且您也不需要指定参数中的id,您将能够执行以下操作:

<textarea style="width:500px; height: 150px;"> This is some text</textarea>
<br />
<input type="button" value="Click Me"  onclick="insertText('\n message1', this);" />
<input type="button" value="Click Me 2" onclick="insertText('\n message2', this);" />

功能如下:

function insertText(mess, btn) {
    var textbox = $(btn).prev('textarea');
    ....

希望它能帮助您找到最佳解决方案:)