使用jquery从多行<p> aragraph中获取随机行?

时间:2015-05-31 23:06:01

标签: javascript jquery

是否可以从包含长篇故事的段落中获取随机行?

1 个答案:

答案 0 :(得分:1)

&#13;
&#13;
function showLines() {
  var lines = getLines();
  
    lines = lines.map(function(line) {
      return line.map(function(span) {
        return span.innerText;
      }).join(' ')
    });
  return lines;
}

function splitLines() {
  var p = document.getElementsByTagName('p')[0];
  p.innerHTML = p.innerText.split(/\s/).map(function(word) {
    return '<span>' + word + '</span>'
  }).join(' ');
}



function getLines() {
  var lines = [];
  var line;
  var p = document.getElementsByTagName('p')[0];
  var words = p.getElementsByTagName('span');
  var lastTop;
  for (var i = 0; i < words.length; i++) {
    var word = words[i];
    if (word.offsetTop != lastTop) {
      lastTop = word.offsetTop;
      line = [];
      lines.push(line);
    }
    line.push(word);
  }
  return lines;
}
splitLines();
var lines = showLines();
console.log(lines);
var randomLine = lines[Math.floor(Math.random()*lines.length)];
console.log(randomLine);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<p id="para"> This is a test. Is it? Yes, it is indeed! 
You might ask, is this a sentence? To which I would reply 
with a resounding "YES"!!!This is a test. Is it? Yes, it is indeed! 
You might ask, is this a sentence? To which I would reply 
with a resounding "YES"!!!</p>
&#13;
&#13;
&#13;

请参阅How to split an HTML paragraph up into its lines of text with JavaScriptGet random item from JavaScript array