使用jQuery删除HTML元素之间的空格和换行符 [英] Remove whitespace and line breaks between HTML elements using jQuery
本文介绍了使用jQuery删除HTML元素之间的空格和换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用jQuery,我想删除HTML标记之间的空格和换行符。
Using jQuery, I'd like to remove the whitespace and line breaks between HTML tags.
var widgetHTML = ' <div id="widget"> <h2>Widget</h2><p>Hi.</p> </div>';
应该是:
alert(widgetHTML); // <div id="widget"><h2>Widget</h2><p>Hi.</p></div>
我认为我需要的模式是:
I think the pattern I will need is:
>[\s]*<
这可以在不使用正则表达式的情况下完成吗?
Can this be accomplished without using regex?
推荐答案
我尝试了用户76888布局的技术并且运行良好。为方便起见,我将它打包成jQuery插件,并认为社区可能喜欢它,所以在这里:
I tried the technique that user76888 laid out and it worked nicely. I packaged it into a jQuery plugin for convenience, and thought the community might enjoy it, so here:
jQuery.fn.cleanWhitespace = function() {
this.contents().filter(
function() { return (this.nodeType == 3 && !/\S/.test(this.nodeValue)); })
.remove();
return this;
}
要使用它,只需将其包含在脚本标记中,然后选择一个标记用jQuery清理并像这样调用函数:
To use this, just include it in a script tag, then select a tag to clean with jQuery and call the function like so:
$('#widget').cleanWhitespace();
这篇关于使用jQuery删除HTML元素之间的空格和换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文