微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐