简体   繁体   English

将textarea内容转换为html

[英]Convert textarea content to html

I need to make a simple Javascript converter, which would turn <textarea> input into html-formatted list. 我需要制作一个简单的Javascript转换器,它将<textarea>输入转换为html格式的列表。

This is how a sample input would look: 这是示例输入的外观:

Brand: Brand1
  Model1 /Model2 /Model3 /Model4 /Model5 /Model6 /
Brand: Brand2
  Model1 /Model2 /Model3 /Model4 /Model5 /Model6 /

And this would be the html after conversion: 这将是转换后的html:

<h3>Brand1</h3>
<ul>
  <li>Model1</li>
  <li>Model2</li>
  <li>Model3</li>
  <li>Model4</li>
  <li>Model5</li>
  <li>Model6</li>
</ul>
<h3>Brand2</h3>
<ul>
  <li>Model1</li>
  <li>Model2</li>
  <li>Model3</li>
  <li>Model4</li>
  <li>Model5</li>
  <li>Model6</li>
</ul>

Could any one provide some sample code to do that? 有人可以提供一些示例代码来做到这一点吗? Thanks a lot 非常感谢

jQuery would be the easy way to do this, but if you're forced to do it with pure Javascript, you'll have something that looks like this: jQuery是执行此操作的简单方法,但是如果您被迫使用纯Javascript执行此操作,则将具有以下内容:

HTML: HTML:

<textarea id="input" rows="5" cols="60">Brand: Brand1
    Model1 /Model2 /Model3 /Model4 /Model5 /Model6
    Brand: Brand2
    Model1 /Model2 /Model3 /Model4 /Model5 /Model6
</textarea>

<input id="convertButton" type="button" value="convert" />

<div id="output"></div>

Javascript: Javascript:

var convertButton = document.getElementById('convertButton');

convertButton.onclick = function(){
    var input = document.getElementById('input');
    var output = document.getElementById('output');

    var lines = input.value.split( '\n' );
    var html = '';
    for( var i=0; i<lines.length; i++ ) {
        if( lines[i].indexOf('Brand')===0 ) {
            var brand = lines[i].split(':')[1];
            html += '<h3>' + brand + '</h3>';
        }
        if( lines[i].indexOf('/')!==-1 ) {
            var models = lines[i].split('/');
            html += '<ul><li>' + models.join('</li><li>') + '</li></ul>';
        }
    }
    output.innerHTML = html;
};​

Note that this solution doesn't do a lot of error checking, and it would get pretty confused if you weren't careful with your input, but it should give you a starting place to do what you want. 请注意,此解决方案不会进行大量错误检查,如果您不小心输入内容,将会感到很困惑,但是它应该为您提供了一个开始执行所需内容的起点。 See a live demo here: http://jsfiddle.net/GUQXf/4/ 在此处观看现场演示: http : //jsfiddle.net/GUQXf/4/

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

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