在每行中包含contenteditable div中的文本

时间:2013-10-01 05:35:21

标签: javascript html

我正在研究像C ++基于Web的IDE。当我试图将文本文件附加到我的contenteditable div(打开文件按钮)时,我有一些问题。 DOM结构必须类似于

<div id = "board_code">
  <div>text in row1</div>
  <div>text in row2</div>
  <div>text in row3</div>
</div>

JS

  function readSingleFile(evt) {

    var f = evt.target.files[0];
      console.log(f);
       if (!f) {
        alert("Failed to load file");
           return;
    } 
      if (f.name.indexOf('.txt') == -1) {
            alert(f.name + " is not a valid text file.");
             return;     
                  }    

      var r = new FileReader();
      r.onload = function(e) { 
          var contents = e.target.result;
          contents = contents.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/\r\n/,'<br>');;
        alert( "Got the file.n" 
              +"name: " + f.name + "n"
              +"type: " + f.type + "n"
              +"size: " + f.size + " bytesn"
              + "contents: " + contents
        );
          document.getElementById('board').innerHTML = contents;
      }
      r.readAsText(f);

  }

  document.getElementById('fileinput').addEventListener('change', readSingleFile, false);

http://jsfiddle.net/88vtR/32/

如何在将每个行中的文本附加到DOM之前将其包装在div中?

1 个答案:

答案 0 :(得分:0)

你可以试试......

function readSingleFile(evt) {

      var f = evt.target.files[0];
      //console.log(f);
      if (!f) {
          alert("Failed to load file");
          return;
      }
      if (f.name.indexOf('.txt') == -1) {
          alert(f.name + " is not a valid text file.");
          return;
      }

      var r = new FileReader();
      r.onload = function (e) {
          var contents = e.target.result; //.replace("\r\n","<br/>");
          contents = contents.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
          alert("Got the file.n" + "name: " + f.name + "n" + "type: " + f.type + "n" + "size: " + f.size + " bytesn" + "contents: " + contents);


          var tmpSent = "";
          var newContents = "";
          for (var i = 0; i < contents.length; i++) {
              if(contents.charAt(i) == '\n') {
                  newContents += "<div>"+tmpSent+"</div>";
                  tmpSent = "";
              }
              else
                  tmpSent += contents.charAt(i);
          };
          if(tmpSent.length>0)
                  newContents += "<div>"+tmpSent+"</div>";

          console.log(newContents);
          document.getElementById('board').innerHTML = newContents;
      }
      r.readAsText(f);

  }

  document.getElementById('fileinput').addEventListener('change', readSingleFile, false);

这是小提琴链接...... jsfiddle