简体   繁体   English

HTML textarea:使用 JavaScript 获取包装文本?

[英]HTML textarea: use JavaScript to get wrapped text?

If I've got a textarea like this:如果我有这样的文本区域:

<textarea id="foo" cols=80 wrap="hard"></textarea>

Is there any way, using JavaScript, to grab the hard-wrapped text?有没有办法使用 JavaScript 来抓取硬包装的文本?

I've tried the obvious $("#foo").val() , but that returns the unwrapped text.我已经尝试了明显的$("#foo").val() ,但这会返回未包装的文本。

For example, if the textarea is:例如,如果 textarea 是:

<textarea id="bar" cols=5 wrap="hard">a b c d e f</textarea>

The browser will wrap the text to:浏览器会将文本换行为:

a b c
d e f

And I was some way to grab that text – "abc\\nd ef" (which, because of wrap=hard , is the text that would be sent if the <textarea… was submitted in a <form… ).我想通过某种方式来获取该文本—— "abc\\nd ef" (由于wrap=hard ,如果<textarea…<form…提交,则该文本将被发送)。

Since the formatting is done by the browser on submit, your best bet will be to have the browser submit, but to a location of your choice such as an iframe where you can extract the formatted text from the form or url parameters.由于格式是在提交时由浏览器完成的,因此最好的办法是让浏览器提交,但提交到您选择的位置,例如 iframe,您可以在其中从表单或 url 参数中提取格式化文本。

<html><body>
    <script type="text/javascript">
        function getURLParameter(qs, name)
        {
          var pattern = "[\\?&]"+name+"=([^&#]*)";
          var regex = new RegExp( pattern );
          var res = regex.exec( qs );
          if (res == null)
            return "";
          else
            return res[1];
        }
        function getHardWrappedText(){
            if (top.location.href !== window.location.href) return;
            var frm_url = document.getElementById('ifrm').contentDocument.URL;
            if (frm_url.indexOf('http') < 0) return;
            var text = unescape(getURLParameter(document.getElementById('ifrm').contentDocument.URL, 'bar')).replace(/\+/g,' ');
            alert(text)
        }
    </script>
    <form name="main" method="get" target="ifrm">
        <textarea id="bar" name="bar" cols=5 wrap="hard">a b c d e f</textarea>
        <input type="submit">
    </form>
    <iframe id="ifrm" name="ifrm" onload="getHardWrappedText();" style="display:none;"></iframe>
</body></html>

Edit 2编辑 2

The only solution that i can propose is to create a hidden iframe with a name, and target the form submit to that frame.我可以提出的唯一解决方案是创建一个带有名称的隐藏 iframe,并将表单提交到该框架。 Then the iframe can communicate with its parent throught the window.parent and provide the returned text (which will include the new lines as the form has been normally submitted..)然后 iframe 可以通过window.parent与其父级通信并提供返回的文本(其中将包括新行,因为表单已正常提交..)

of course the submit could be called by a script if you wished ..当然,如果您愿意,可以通过脚本调用提交..

the following i have strike-through since it does not apply to this case.. a generic way to do this would be 以下我有删除线,因为它不适用于这种情况.. 一个通用的方法是

 
 
 
  
  
  alert( $('<div/>').append($('#foo').clone()).html() );
 
 
 

what this does is 这是做什么的

Create a new div (in memory) 创建一个新的 div(在内存中)

 
 
 
 
  
  
  $('<div/>')
 
 
 

clone the desired element #foo and append it to the div we created 克隆所需的元素 #foo并将其附加到我们创建的 div

 
 
 
 
  
  
  .append( $('#foo').clone() )
 
 
 

extract the inner html (but since we are dealing with the div that we wrapped around our element, we get the elements html .. 提取内部 html(但由于我们正在处理包裹在元素周围的 div,因此我们得到元素 html ..

 
 
 
 
  
  
  .html()
 
 
 

[EDIT] [编辑]
obviously i misunderstood .. to get the inside text of an element use the .text() method so 显然我误解了 .. 要获取元素的内部文本,请使用 .text() 方法,因此

 
 
 
  
  
  $('#foo').text();
 
 
 

I'm assuming that you know the dimensions of the text area (if not, you can probably just get them from the DOM).我假设您知道文本区域的尺寸(如果没有,您可以从 DOM 中获取它们)。

Use this to split the string.使用它来分割字符串。 Go to the xth char (in your example the 5th), and see if the next char is a space.转到第 x 个字符(在您的示例中是第 5 个字符),然后查看下一个字符是否为空格。 If so (or if there are no spaces in the preceding segment), this is where you split.如果是这样(或者如果前面的段中没有空格),这就是您拆分的地方。 Otherwise, you find the preceding space and split there.否则,您会找到前面的空格并在那里拆分。

Wrap this in a function and you could add in some recursion to find the nth line.将其包装在一个函数中,您可以添加一些递归以找到第 n 行。

I don't think it's possible out of the box You could wrap the text yourself using textarea's cols value.我认为不可能开箱即用您可以使用 textarea 的cols值自己包装文本。 From the HTML point of view the text in textarea is not wrapped.从 HTML 的角度来看,textarea 中的文本没有被换行。 It's just how it's being displayed for you to be able to read it better.这只是它的显示方式,以便您能够更好地阅读它。

PS.附注。 If you are using jQuery you should use $('#foo') instead of $('[id=foo]') selector as it's much faster (and shorter).如果您使用 jQuery,您应该使用$('#foo')而不是$('[id=foo]')选择器,因为它更快(也更短)。

这有点麻烦,但是您可以在服务器上创建一个脚本,该脚本以某种格式(JSON、纯文本、任何适合您的格式)打印出发布到它的任何内容,并在您需要时通过 AJAX 将您的 textarea 发布到该脚本得到它的内容。

With modern browsers the wrapped text can be found in FormData :使用现代浏览器,可以在FormData 中找到换行的文本:

new FormData(document.querySelector('form')).get('name')

This appears to match what is submitted (the wrapping as shown or the unwrapped value ).这似乎与提交的内容相匹配(如图所示的包装或未包装的值)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM