使用 jQuery 删除 HTML 元素之间的空格和换行符 [英] Remove whitespace and line breaks between HTML elements using jQuery

查看:25
本文介绍了使用 jQuery 删除 HTML 元素之间的空格和换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 jQuery,我想删除 HTML 标签之间的空格和换行符.

var widgetHTML = ' 

<h2>小部件</h2><p>嗨.</p>

';

应该是:

alert(widgetHTML);//<div id="widget"><h2>Widget</h2><p>Hi.</p></div>

我认为我需要的模式是:

>[s]*<

这可以不使用正则表达式来完成吗?

解决方案

我尝试了 user76888 提出的技术,效果很好.为了方便,我把它打包成一个jQuery插件,认为社区可能会喜欢它,所以在这里:

jQuery.fn.cleanWhitespace = function() {this.contents().filter(function() { return (this.nodeType == 3 && !/S/.test(this.nodeValue));}).消除();返回这个;}

要使用它,只需将它包含在脚本标签中,然后选择一个标签以使用 jQuery 清理并像这样调用函数:

$('#widget').cleanWhitespace();

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>';

Should be:

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?

解决方案

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;
}

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆