逐行从textarea获取文本? [英] Get the text from textarea line by line?

查看:161
本文介绍了逐行从textarea获取文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HTML代码

<textarea id="test"></textarea>
<button id="button_test">Ok</button>

Javascript

Javascript

  $(document).ready(function()
  {
     $("#test").val("123e2oierhqwpoiefdhqwopidfhjcospid");
  });
 $("#button_test").on("click",function()
      {
      var as=document.getElementById("test").value;
      console.log(as);
      });

我们可以使用val和split函数逐行获取textarea的值。但是
是否可以逐行从textarea获取值很长的单词?。在示例中,我需要输出 123e2oierhqwpoiefdhqwo pidfhjcospid 作为单独的值。
Jsfiddle链接此处

We can get the values from textarea line by line using val and split functions. But Is it possible to get the value from textarea line by line for very long word?.In the example i need to get the output as 123e2oierhqwpoiefdhqwo and pidfhjcospid as separate values. Jsfiddle link here

推荐答案

你可以使用这样的东西。这会将换行符插入到textarea中。

You can use something like this. This will insert line breaks into into the textarea.

致谢: https://stackoverflow.com/a/4722395/4645728

$(document).ready(function() {
    $("#test").val("123e2oierhqwpoiefdhqwopidfhjcospid");
});

$("#button_test").on("click", function() {
    ApplyLineBreaks("test");
    var as = document.getElementById("test").value;
    console.log(as);
});

//https://stackoverflow.com/a/4722395/4645728
function ApplyLineBreaks(strTextAreaId) {
    var oTextarea = document.getElementById(strTextAreaId);
    if (oTextarea.wrap) {
        oTextarea.setAttribute("wrap", "off");
    } else {
        oTextarea.setAttribute("wrap", "off");
        var newArea = oTextarea.cloneNode(true);
        newArea.value = oTextarea.value;
        oTextarea.parentNode.replaceChild(newArea, oTextarea);
        oTextarea = newArea;
    }

    var strRawValue = oTextarea.value;
    oTextarea.value = "";
    var nEmptyWidth = oTextarea.scrollWidth;
    var nLastWrappingIndex = -1;
    for (var i = 0; i < strRawValue.length; i++) {
        var curChar = strRawValue.charAt(i);
        if (curChar == ' ' || curChar == '-' || curChar == '+')
            nLastWrappingIndex = i;
        oTextarea.value += curChar;
        if (oTextarea.scrollWidth > nEmptyWidth) {
            var buffer = "";
            if (nLastWrappingIndex >= 0) {
                for (var j = nLastWrappingIndex + 1; j < i; j++)
                    buffer += strRawValue.charAt(j);
                nLastWrappingIndex = -1;
            }
            buffer += curChar;
            oTextarea.value = oTextarea.value.substr(0, oTextarea.value.length - buffer.length);
            oTextarea.value += "\n" + buffer;
        }
    }
    oTextarea.setAttribute("wrap", "");
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<textarea id="test"></textarea>
<button id="button_test">Ok</button>

这篇关于逐行从textarea获取文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆