且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用jQuery删除HTML元素之间的空格和换行符

更新时间:2023-01-14 15:44:12

我尝试了用户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();