javascript – 逐行从textarea获取文本?

HTML代码

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

使用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链接here

解决方法:

你可以使用这样的东西.这会将换行符插入到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>

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: &lt;span id=&quot...
jQuery 添加水印 &lt;script src=&quot;../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...