简体   繁体   中英

Better way to write this (jQuery)

I a newbie at this so excuse the lack of brevity. I am wondering if there is a better way to write this without repeating myself so much;

 var slider = $('input.slider'), percent = Math.ceil((($(slider).val() - $(slider).attr('min') - 20) / ($(slider).attr('max') - $(slider).attr('min'))) * 100), sliderCSS = { 'background': '-webkit-linear-gradient(left, #6f00e4 0%, #0fe0ba ' + percent + '%, rgba(255, 255, 255, 0.1) ' + percent + '%)' }; $(slider).each(function() { $(this).css(sliderCSS); }).on("input", function() { $(this).css(newSliderCSS); }); 

I have try to store the repetitions in variables then try to call them as below but this does not work as expected.

 var slider = $('input.slider'), percent = Math.ceil((($(slider).val() - $(slider).attr('min') - 20) / ($(slider).attr('max') - $(slider).attr('min'))) * 100), sliderCSS = { 'background': '-webkit-linear-gradient(left, #6f00e4 0%, #0fe0ba ' + percent + '%, rgba(255, 255, 255, 0.1) ' + percent + '%)' }; $(slider).each(function() { $(this).css(sliderCSS); }).on("input", function() { $(this).css(newSliderCSS); }); 

Where am I botching this? Thanks.

I would suggest reading up on lexical scope. You can read more about scope here .

This should clean it up a bit.

EDIT: I missed the reference to "this" in your example when I first looked. Here is an updated answer.

var slider = $('input.slider');

function calculatePercent(value, min, max) {
    return Math.ceil(((value - min - 20) / (max - min)) * 100);
}

function buildCss(value, min, max) {
    var percent = calculatePercent(value, min, max);
    return '-webkit-linear-gradient(left, #6f00e4 0%, #0fe0ba ' + percent + '%, rgba(255, 255, 255, 0.1) ' + percent + '%)';
}

$(slider).each(function() {
    $(this).css('background', buildCss(this.value, this.min, this.max));
    $('#mainSendAmount').text(this.value);
}).on("input", function() {
    $(this).css('background', buildCss(this.value, this.min, this.max));
});

Here's how I would simplify:

var slider = $('input.slider');

$(slider).each(function() {
  var percent = Math.ceil(((this.value - this.min - 20) / (this.max - this.min)) * 100);

  $(this).css('background', makeGradient(percent));
  $('#mainSendAmount').text(this.value);

  $(this).on('input', function() {
    $(this).css('background', makeGradient(percent));
  });
});

var makeGradient = function(percent) {
  return '-webkit-linear-gradient(left, #6f00e4 0%, #0fe0ba ' + percent + '%, rgba(255, 255, 255, 0.1) ' + percent + '%)';
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM