如何使用 javascript 从 `<pre></pre>` 中删除 `<code></code>`?
How do I remove `<code></code>` from `<pre></pre>` with javascript?
markdown 中的三重反引号呈现为 <pre><code class="...">...</code></pre>
。更具体地说,
# in markdown
```java
```
# render as
<pre>
<code class="java">
...
</code>
</pre>
# my expecting result (for Google code prettify):
<pre class="prettyprint linenums lang-java">
...
</pre>
我目前的解决方案是添加以下代码,但它不起作用。
<script src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js?skin=son-of-obsidian></script>
<script type="text/javascript">
jQuery(document).ready(function () {
$('pre code').each(function() {
var code = $(this).html();
var lang = $(this).attr('class');
if (lang) {
$(this).parent().attr('class', 'prettyprint linenums lang-'+lang).html(code);
}
});
prettyPrint();
});
</script>
如何删除 <code class="...">...</code>
?
我使用 SyntaxHighlighter <pre class="brush: java">...</pre>
在 WordPress
+ Windows Live Writer
+ PreCode
(基于 SyntaxHighlighter)中突出显示我的代码块。
目前,我转向markdown。要在降价中插入代码块,我使用
```java
code here
```
# OR
<pre class="brush: java">
code here
</pre>
它们都不适合我,因为 SyntaxHighlighter 要求 <pre></pre>
内的所有左尖括号都应该 HTML 转义。
因此,我安装了Google code prettify,但遇到了上述问题(不兼容)。
试试下面的方法,让我知道它是否适合你。
$('pre').each(function() {
var el = $(this).find('code');
var code = el.html();
var lang = el.attr('class');
if (lang) {
$(this).addClass('prettyprint linenums lang-' + lang).html(code);
}
});
您忘记从 pre 元素中删除原始代码对象,导致代码重复。您应该调用 $(this).remove();
来删除旧代码对象。
markdown 中的三重反引号呈现为 <pre><code class="...">...</code></pre>
。更具体地说,
# in markdown
```java
```
# render as
<pre>
<code class="java">
...
</code>
</pre>
# my expecting result (for Google code prettify):
<pre class="prettyprint linenums lang-java">
...
</pre>
我目前的解决方案是添加以下代码,但它不起作用。
<script src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js?skin=son-of-obsidian></script>
<script type="text/javascript">
jQuery(document).ready(function () {
$('pre code').each(function() {
var code = $(this).html();
var lang = $(this).attr('class');
if (lang) {
$(this).parent().attr('class', 'prettyprint linenums lang-'+lang).html(code);
}
});
prettyPrint();
});
</script>
如何删除 <code class="...">...</code>
?
我使用 SyntaxHighlighter <pre class="brush: java">...</pre>
在 WordPress
+ Windows Live Writer
+ PreCode
(基于 SyntaxHighlighter)中突出显示我的代码块。
目前,我转向markdown。要在降价中插入代码块,我使用
```java
code here
```
# OR
<pre class="brush: java">
code here
</pre>
它们都不适合我,因为 SyntaxHighlighter 要求 <pre></pre>
内的所有左尖括号都应该 HTML 转义。
因此,我安装了Google code prettify,但遇到了上述问题(不兼容)。
试试下面的方法,让我知道它是否适合你。
$('pre').each(function() {
var el = $(this).find('code');
var code = el.html();
var lang = el.attr('class');
if (lang) {
$(this).addClass('prettyprint linenums lang-' + lang).html(code);
}
});
您忘记从 pre 元素中删除原始代码对象,导致代码重复。您应该调用 $(this).remove();
来删除旧代码对象。