javascript - 如何使用 jquery 制作一个简单的 prettyprint <pre>

标签 javascript jquery html pretty-print pre

http://jsfiddle.net/JamesKyle/L4b8b/

我正在尝试使用 jQuery 创建一个极其简单的 prettyprint 函数,但我不知道如何查找元素、属性和值(在 jsfiddle 中显示)。

I am trying to accomplish the following:

  1. Wrap elements with <span class="element" />
  2. Wrap attributes with <span class="attribute" />
  3. Wrap values with <span class="value" />
  4. Replace < with &lt
  5. Replace > with &gt

这是我当前拥有的 jQuery:

$(document).ready(function() {

    $('pre.prettyprint').each(function() {

        $(this).css('whitespace','pre-line');
        /* Why isnt ^this^ working? */

        var code = $(this).html();

        // How should I define the following

        var element = $(code).find(/* ELEMENTS */);
        var attribute = $(code).find(/* ATTRIBUTES */);
        var value = $(code).find(/* Values */);

        $(element).wrap('<span class="element" />');
        $(attribute).wrap('<span class="attribute" />');
        $(value).wrap('<span class="value" />');

        $(code).find('<').replaceWith('&lt');
        $(code).find('>').replaceWith('&gt');
    });
});

正在尝试格式化:

<pre class="prettyprint">
    <a href="http://website.com">Visit Website</a>
    <a href="#top">Back to Top</a>
</pre> 

进入这个:

<pre class="prettyprint">
    <span class="element">a <span class="attribute">href</span>=<span class="value">”http://website.com”</span></span>Visit Website<span class="element">/a</span>
    <br/>
    <span class="element">a <span class="attribute">href</span>=<span class="value">”#top”</span></span>Back to Top<span class="element">/a</span>
</pre>

提前谢谢你!

You can see the jsfiddle here: http://jsfiddle.net/JamesKyle/L4b8b/

最佳答案

真正的魔力在于处理任意属性的标签。这是简单的“ anchor ”版本:jsFiddle

$('pre.prettyprint').each(function() {
    $('a').each(function(){
        $anchor = $(this);
        html = '<span class="element">&lt;a ';
        html += '<span class="attribute">href</span>=<span class="value">"' + $anchor.attr('href') + '"&gt;</span>';
        html += '</span>' + $anchor.text() + '<span class="element">&lt;/a&gt;</span>'
        $anchor.replaceWith(html);
    });
});

关于javascript - 如何使用 jquery 制作一个简单的 prettyprint <pre>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8336188/

相关文章:

javascript - 删除 javascript 创建的内容

css - 如何仅使用 HTML 和 CSS 将外部 2 列滑动到中心列下方?

javascript - PHP 页面上未加载 Highcharts

javascript - 向折线图添加工具提示未显示

javascript - express .js : calling internal services

javascript - jquery 在多个 DIV 上滑动效果并嵌入关闭效果

javascript - JQuery 如何获取生成的 html 的 &lt;title&gt;

javascript - 无法通过 js .focus() 捕获所需元素的焦点

jQuery 幻灯片效果问题

javascript - 使用 javascript 在图像上标记区域