在<pre> with <span>

时间:2016-06-10 16:08:37

标签: jquery

I am looking for a jquery solution to dynamically wrap the contents of my<pre> code which is written as below, to wrap each line with a <span> and </span> element so that my CSS styling for line numbers works.

Any ideas on how to do this?

<pre>
This is the first line of pre text.
This is the 2nd line...
This is the 3rd line etc etc you get the ideas...
<pre>

The above needs to be amended by jQuery to become:

<pre>
<span>This is the first line of pre text.</span>
<span>This is the 2nd line...</span>
<span>This is the 3rd line etc etc you get the ideas...</span>
<pre>

2 个答案:

答案 0 :(得分:1)

Use html() method with callback in jQuery to iterate and update content, where String#split and Array#join methods van use for generate the content.

$('pre').html(function(i, old) {
  return '<span>' + old.split('\n').join('</span>\n<span>') + '</span>';
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre>
This is the first line of pre text.
This is the 2nd line...
This is the 3rd line etc etc you get the ideas...
</pre>

答案 1 :(得分:-1)

您可以使用Twitter的自举中继。 以下是您需要输入到HTML部分的代码:

<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

将其粘贴到HTML部分的头部,这样可以更容易使用。