Jam*_*yle 7 javascript jquery pretty-print pre
我试图用jQuery创建一个非常简单的prettyprint函数,但我不知道如何查找元素,属性和值(显示在jsfiddle中).
我想完成以下事项:
- 包裹元素
<span class="element" />- 用于换行属性
<span class="attribute" />- 用值换行值
<span class="value" />- 替换
<为<- 替换
>为>
这是我当前的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('<');
$(code).find('>').replaceWith('>');
});
});
Run Code Online (Sandbox Code Playgroud)
哪个试图格式化:
<pre class="prettyprint">
<a href="http://website.com">Visit Website</a>
<a href="#top">Back to Top</a>
</pre>
Run Code Online (Sandbox Code Playgroud)
进入这个:
<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>
Run Code Online (Sandbox Code Playgroud)
提前谢谢你!
你可以在这里看到jsfiddle:http: //jsfiddle.net/JamesKyle/L4b8b/
真正的魔力在于处理任意属性的标签。这是简单的“锚”版本:jsFiddle
$('pre.prettyprint').each(function() {
$('a').each(function(){
$anchor = $(this);
html = '<span class="element"><a ';
html += '<span class="attribute">href</span>=<span class="value">"' + $anchor.attr('href') + '"></span>';
html += '</span>' + $anchor.text() + '<span class="element"></a></span>'
$anchor.replaceWith(html);
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3153 次 |
| 最近记录: |