2017-01-16 36 views
2

我在下面的鏈接上有代碼,我需要在任何地方多次使用它。我爲酒吧設定了不同的價值,當然這是錯誤的。所以,不好的答案是爲每個跨度設置id併爲它們複製代碼幾次。如何在jQuery中創建可重用的代碼?

請給我一個提示如何重寫代碼,我不需要一遍又一遍地重複。

P.S.是的,我知道progressbar.js和其他庫,但在這個地方,我需要處理HTML元素欄。

$(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

您可能想要在問題中包含HTML和CSS,而不是要求jsfiddle充分理解。 – 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/

設置變量$跨度和$ barvalue。

$(".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(" %"); 
     } 
    }); 

    });