2017-01-16 13 views
2

私は下のリンクにコードを書いていますので、どこでも何度か使用する必要があります。私はバーのために異なった価値を設定しました、もちろん間違っています。だから、悪い答えはそれぞれのスパンにidを設定し、それらのコードを何回かコピーします。jQueryで再利用可能なコードを作成するには?

何度も何度も繰り返す必要のないコードを書き換える方法を教えてください。

P.S.はい、私はprogressbar.jsと他のライブラリについて知っていますが、この場所ではhtml要素からbarを処理する必要があります。 $スパンと$ barvalueため

$(document).ready(function() { 
    $(".blackbar > span").each(function() { 
    var percentWidth = $('.blackbar > span').data('width'); 
    $(this).animate({ 
     width: $(this).data("width") + "%" 
    }, 800); 
    $({ 
     countNum: 0 
    }).animate({ 
     countNum: percentWidth 
    }, { 
     duration: 800, 
     easing: 'linear', 
     step: function() { 
     $('.barvalue').text(Math.floor(this.countNum)).append(" %"); 
     }, 
     complete: function() { 
     $('.barvalue').text(this.countNum).append(" %"); 
     } 
    }); 

    }); 
}); 

JSFiddle example

+0

あなたがかもしれません完全な理解のためにjsfiddleを必要とするのではなく、HTMLとCSSを質問に含めることもできます。 – Luke

答えて

1

あなたは各.barboxをループにしたい、その後、バー、値のスパンのためのスパンを見つけ、それらを適切に使用して...

$(document).ready(function(){ 
    $(".barbox").each(function() { 
     var $barbox = $(this); 
     var $barSpan = $barbox.find('.blackbar > span'); 
     var $barValue = $barbox.find('.barvalue'); 
     var percentWidth = $barSpan.data('width'); 
     $barSpan.animate({ 
       width: percentWidth + "%" 
     }, 800); 
     $({countNum: 0}).animate({countNum: percentWidth}, { 
      duration: 800, 
      easing: 'linear', 
      step: function() { 
       $barValue.text(Math.floor(this.countNum) + " %"); 
      }, 
      complete: function() { 
       $barValue.text(this.countNum + " %"); 
      } 
     }); 
    }); 
}); 

https://jsfiddle.net/vsp6vuuh/2/

1

https://jsfiddle.net/SeanWessell/8919job4/

セット変数。

$(".blackbar > span").each(function() { 
    var $span = $(this); 
    var $barvalue = $span.closest('.b-item__barbox.barbox').find('.barvalue'); 
    var percentWidth = $span.data('width'); 
    $span.animate({ 
     width: percentWidth + "%" 
    }, 800); 
    $({ 
     countNum: 0 
    }).animate({ 
     countNum: percentWidth 
    }, { 
     duration: 800, 
     easing: 'linear', 
     step: function() { 
     $barvalue.text(Math.floor(this.countNum)).append(" %"); 
     }, 
     complete: function() { 
     $barvalue.text(this.countNum).append(" %"); 
     } 
    }); 

    }); 
関連する問題