2

我编写了以下函数来从 SharePoint 网站中的 html 代码中删除不间断空格(每当您打开母版页或页面布局时,SharePoint 设计器都会在您编写的任何代码中使用不间断空格!您最终会花费所有时间返回并删除它们)。

无论如何,它似乎太长了,我对 jQuery 还是很陌生,想知道是否有更简洁的方法来执行相同的任务。

<script type="text/javascript">
    $(function(){
            $('h1').each( function() {  
        var $h = $(this);  
        var html = $h.html();  
        html = html.replace( '&nbsp;', '' );  
        $h.html( html );  
    });
}); 
$(function(){
            $('h2').each( function() {  
        var $h = $(this);  
        var html = $h.html();  
        html = html.replace( '&nbsp;', '' );  
        $h.html( html );  
    });
}); 
$(function(){
            $('h3').each( function() {  
        var $h = $(this);  
        var html = $h.html();  
        html = html.replace( '&nbsp;', '' );  
        $h.html( html );  
    });
}); 
$(function(){
            $('h4').each( function() {  
        var $h = $(this);  
        var html = $h.html();  
        html = html.replace( '&nbsp;', '' );  
        $h.html( html );  
    });
}); 
    $(function(){
            $('p').each( function() {  
        var $h = $(this);  
        var html = $h.html();  
        html = html.replace( '&nbsp;', '' );  
        $h.html( html );  
    });
}); 

    </script>
4

3 回答 3

4
$(function() {
    $('h2, h3, h4, p').each(function() {
        var $h = $(this);
        var html = $h.html();
        html = html.replace( ' ', '' );
        $h.html( html );
    });
})
于 2009-09-24T09:37:28.233 回答
3

您可以将所有这些组合为一个$(function() { ... }); 没有太多理由将这些调用中的每一个都包装在其自己的文档就绪事件处理程序中。

此外,您在许多元素上调用相同的函数,您可以将您的选择器与其他人提出,的更短的结果结合起来。$('h2,h3,h4,h5').each(function() {....});

缩短函数体:

var html = $h.html();
html = html.replace('&nbsp;', '');

可以在一行上完成:

var html = $h.html().replace('&nbsp;', '');

并且由于您只引用它足够长的时间来调用另一个函数 - 它甚至不需要存储在自己的变量中:

$h.html($h.html().replace('&nbsp;', ''));

或者如果使用 jQuery > 1.4 ,请使用新的函数语法:

$h.html(function(index, oldHtml) { return oldHtml.replace('&nbsp;', ''); });

当然-如果需要,您的多行方法为您提供了更多插入调试代码的位置,我通常在验证它有效后手动压缩这种东西。

使它成为一个插件

下一种方法对于这种情况来说有点矫枉过正,但可能会更深入地了解 jQuery 并创建“可重用”代码。

// generic replace in html function - proxies all the arguments to 
// .replace()
$.fn.replaceHtml = function() {
  var replaceArgs = arguments;
  // jQuery 1.4 allows
  return this.html(function(idx, oldHtml) {
    return oldHtml.replace.apply(oldHtml, replaceArgs);
  });
  // older versions / another way to write it
  // return this.each(function() { 
  //   var $t = $(this), html = $t.html();
  //   $t.html(html.replace.apply(html, replaceArgs));
  // });
};

// single task that uses the replaceHtml function
$.fn.removeNBSP = function() {
  return this.replaceHtml('&nbsp;', '');
};

$('h1,h2,h3,h4,h5,p').removeNBSP(); 
于 2009-09-24T10:21:12.000 回答
1
$(function() {
   $('h2, h3, h4, p').html(function(){ return $(this).html().replace(" ", "") }) 
});
于 2009-09-24T09:45:19.747 回答