使用Beautify.js來美化你的jQuery代碼
日期:2011/11/15 來源:GBin1.com
使用程序或者某些工具自動生成的Javascript格式有時候可能會非常糟糕,這個時候如果我們擁有一個可以自動幫助你美化代碼的工具將會非常的給力!今天我們介紹使用Beautify.js來幫助你自動規整jQuery代碼。
Javascript代碼:
$(document).ready(function() {
$('.beautify').each(function()
{
console.log(this);
beautify(this);
});
});
以上代碼查詢DOC中的class為beautify的節點,然后調用beautify。
HTML
<B> CSS Code </B>
<pre>body{color:#fff;font-size:12px}</pre>
<pre class="beautify">body{color:#fff;font-size:12px}</pre>
<B> jQuery Code </B>
<pre>$('#gbin1').html('Just a test for beautify.js, enjoy!').animate({fontSize: "15px"}, 500);</pre>
<pre class="beautify">$('#gbin1').html('Just a test for beautify.js, enjoy!').animate({fontSize: "15px"}, 500);</pre>
修改了的beautify(),然后保存為gbbeautify.js,如下:
var the = {
beautify_in_progress: false
};
// this dummy function alleviates Chrome large string corruption by probably shoveling the corruption bug to some other area
if (/chrome/.test(navigator.userAgent.toLowerCase())) {
String.prototype.old_charAt = String.prototype.charAt;
String.prototype.charAt = function (n) { return this.old_charAt(n); }
}
function unpacker_filter(source) {
var trailing_comments = '';
var comment = '';
var found = false;
do {
found = false;
if (/^\s*\/\*/.test(source)) {
found = true;
comment = source.substr(0, source.indexOf('*/') + 2);
source = source.substr(comment.length).replace(/^\s+/, '');
trailing_comments += comment + "\n";
} else if (/^\s*\/\//.test(source)) {
found = true;
comment = source.match(/^\s*\/\/.*/)[0];
source = source.substr(comment.length).replace(/^\s+/, '');
trailing_comments += comment + "\n";
}
} while (found);
return trailing_comments + source;
}
function beautify(elem) {
if (the.beautify_in_progress) return;
the.beautify_in_progress = true;
// var source = $('#source').val();
var source = $(elem).html();
var indent_size = $('#tabsize').val();
var indent_char = indent_size == 1 ? '\t' : ' ';
var preserve_newlines = $('#preserve-newlines').attr('checked');
var keep_array_indentation = $('#keep-array-indentation').attr('checked');
var brace_style = $('#brace-style').val();
if ($('#detect-packers').attr('checked')) {
source = unpacker_filter(source);
}
var comment_mark = '<-' + '-';
var opts = {
indent_size: indent_size,
indent_char: indent_char,
preserve_newlines:preserve_newlines,
brace_style: brace_style,
keep_array_indentation:keep_array_indentation,
space_after_anon_function:true};
if (source && source[0] === '<' && source.substring(0, 4) !== comment_mark) {
$(elem).html(
style_html(source, opts)
);
} else {
var v = js_beautify(unpacker_filter(source), opts);
$(elem).html(v);
}
the.beautify_in_progress = false;
}
歡迎訪問GBin1.com


浙公網安備 33010602011771號