简体   繁体   English

html-从textarea获取包装文本

[英]html - Get wrapped text from textarea

I'm trying to get the word wrapped line breaks from a textarea without having make any server calls. 我正在尝试从textarea换行换行符,而无需进行任何服务器调用。 This answer gets me 90% of the way there. 这个答案使我有90%的解决方法。 The problem is that the page is reloaded inside of the iframe each time the submit button is clicked. 问题在于,每次单击“提交”按钮时,页面都会在iframe中重新加载。 Here's the code: 这是代码:

 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <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() { var frm_url = document.getElementById('frame').contentDocument.URL; var text = unescape(getURLParameter(document.getElementById('frame').contentDocument.URL, 'text')).replace(/\\+/g, ' '); return text; } function onIFrameLoad() { var text = getHardWrappedText(); console.log(text); } window.onload = function() { console.log("loading") }; </script> <form name="form" method="get" target="frame"> <textarea id="text" name="text" cols=5 wrap="hard">abcde f</textarea> <input type="submit"> </form> <iframe id="frame" name="frame" onload="onIFrameLoad()" style="display:none;"></iframe> </body> </html> 

Clicking on the submit button gives the output: 单击提交按钮将给出输出:

loading
a b c d e 
f

Is there a way to prevent the iframe from reloading the page? 有没有一种方法可以防止iframe重新加载页面?

You have to return a false to the onsubmit event of the form. 您必须向表单的onsubmit事件返回false。

<form name="form" method="get" target="frame" onsubmit="onIFrameLoad">

If it is based on some condition that you do not want to load 如果它是基于某种条件,您不想加载

function onIFrameLoad() {
    var text = getHardWrappedText();
    console.log(text);
    if(text.indexOf('\n')<0) return false;
}

Am just putting a random thing at text.indexOf('\\n')<0 , you can have anything that makes sense or always return false (which looks unlikely) 只是在text.indexOf('\\n')<0放一个随机的东西,您可以拥有任何有意义的东西,或者总是返回false(看起来不太可能)

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

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