在数组javascript中的特定字符串后插入分页符

时间:2015-12-02 17:05:48

标签: javascript jquery string-split

我制作了一个代码,需要在一定数量的新行或单词之后进行分页。我已经设置了一个数组,告诉我它应该在我的元素中切割的位置。正如您在我的https://dev.mysql.com/doc/refman/5.5/en/create-trigger.html中看到的,您可以看到console.log();,表明我需要剪切文字。

我想获得有关如何在</div>的特定字符串后插入结尾array()的帮助。我希望关闭</div>并创建新的<div>

有关代码的更多详细信息

// $(this)
$(this) = $('.c_84');

HTML示例

<div class=" onerow counting_1"><div class="newDiv"></div>
   <div class="onefield c_6937">
      <!-- This is where I want to generate the new divs -->
      <table class="textarea" cellspacing="0" cellpadding="0">
         <tbody>
         <tr>
            <td class="value"><!-- Content String --></td>
         </tr>
         </tbody>
      </table>
   </div>
</div>

到目前为止,这是我的代码逻辑。

// The class c_6937 is the class test in my jsFiddle
// I did this just to remove extra html and focus on the problem

// Start
$(this).find('.c_6937').parent().prepend('<div class="newDiv">');
var countReqNumberOfPages = newChunk.length;
for (var key in newChunk) {
    // If we find the first chunk, insert </div><div class="newDiv"> after it.
}

// End
$(this).find('.c_6937').parent().append('</div>');

是否可以在我的array()中运行str_replace()函数并用完全相同的字符串和结束div替换当前字符串?

编辑1:我在代码中添加了额外的注释,以便更好地理解问题并添加了可能的解决方案。

1 个答案:

答案 0 :(得分:1)

我不确定你是否喜欢这样的事情

<script type="text/javascript">

var wordsPerLine = 15;
var minWordsPerLine = 5;
var linesPerPage = 30;
var linesToStopAfter = [];


function checkForDot(pos,masterArray){
  if(pos < 0){

    return false;
  }
  var line = masterArray[pos];
  if(line.indexOf('.') !== -1){
    return line;
  }
  else{

    return checkForDot(pos-1,masterArray);
  }
}

function chunk(lines) {

  var masterLines = [];
  for (i = 0; i < lines.length; i++) { 

      var sentence = [];
      var wordsList = lines[i].split(" ");
      var wordCount = 0;
      for (j = 0; j < wordsList.length; j++) { 

        if(wordCount >= wordsPerLine){

          wordCount = 0;
          masterLines.push(sentence.join(" "));
          sentence = [];
          sentence.push(wordsList[j]);
        }
        else{

          sentence.push(wordsList[j]);
        }

        wordCount++;        
      }

      masterLines.push(sentence.join(" "));           
  }

    return masterLines
}

$(document).ready(function()
{
    var html = $("#test").html();
    $("#test").html('<div class="newDiv">'+html+'</div>');
    var lines = chunk($("#test").text().split("\n"));
    var count = 0;
    for (k = 0; k < lines.length; k++) { 
      count++;
      if(count >= linesPerPage){
        count = 0;
        linesToStopAfter.push(checkForDot(k,lines));
      }
    }

    for(j=0; j<linesToStopAfter.length;j++)
    {
        toreplace = $("#test").html().replace(linesToStopAfter[j], linesToStopAfter[j]+"</div><div class='newDiv'>");
        $("#test").html(toreplace)
    }
    cleanedhtml = $("#test").html().replace(/<\s*div[^>]*><\s*\/\s*div>/g,"");
    $("#test").html(cleanedhtml)
});

</script>