代码之家  ›  专栏  ›  技术社区  ›  toomanyairmiles

缩短jQuery函数

  •  2
  • toomanyairmiles  · 技术社区  · 16 年前

    <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>
    
    3 回复  |  直到 16 年前
        1
  •  4
  •   Deniz Dogan    16 年前
    $(function() {
        $('h2, h3, h4, p').each(function() {
            var $h = $(this);
            var html = $h.html();
            html = html.replace( ' ', '' );
            $h.html( html );
        });
    })
    
        2
  •  3
  •   gnarf    16 年前

    $(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;', ''));
    

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

    // 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(); 
    
        3
  •  1
  •   Makram Saleh    16 年前
    $(function() {
       $('h2, h3, h4, p').html(function(){ return $(this).html().replace(" ", "") }) 
    });