Problem: I'm working with a jQuery UI slider that uses very large values (range 0-140,000; steps 20,000), and I've modified a solution found elsewhere on Stack Overflow to add labels to the slider. However, that code (see below) adds a label for every number in the 140,000 range. Is there an alternative to the .each() method that would only add a label for every x elements (I'm trying to get a label every 20,000 value)? Or can someone recommend a more intelligent way to go about this?

Javascript:

$( "#slider" ).slider({
    range: "min",
    value: 0,
    min: 0,
    max: 7,
    step: 1
})
.each(function() {

  //
  // Add labels to slider whose values 
  // are specified by min, max and whose
  // step is set to 1
  //

  // Get the options for this slider
  var opt = $(this).data().uiSlider.options;

  // Get the number of possible values
  var vals = opt.max - opt.min;

  // Space out values
  for (var i = 0; i <= vals; i++) {

    var el = $('<label>'+(i+1)+'</label>').css('left',(i/vals*100)+'%');

    $( "#slider" ).append(el);

  }

});
有帮助吗?

解决方案

You should define your actual range in your slider options:

$("#slider").slider({
    range: "min",
    value: 0,
    min: 0,
    max: 140000,
    step: 20000
})

Then use the step option as your increment in the loop:

for (var i = 0; i <= vals; i += opt.step) {...}

Here's a demo fiddle

And the resulting code:

$("#slider").slider({
    range: "min",
    value: 0,
    min: 0,
    max: 140000,
    step: 20000
}).each(function () {
    //
    // Add labels to slider 
    //

    // Get the options for this slider
    var opt = $(this).data().uiSlider.options;

    // Get the number of possible values
    var vals = opt.max - opt.min;

    // Space out values
    for (var i = 0; i <= vals; i += opt.step) {
        var el = $('<label>' + i + '</label>').css('left', (i / vals * 100) + '%');
        $("#slider").append(el);
    }
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top