All my (jQuery UI) single sliders get the same value

我怕爱的太早我们不能终老 提交于 2019-12-11 01:57:28

问题


I want each slider of the same page have it's own value when I slide each one of them.

When I slide one of them, the "slider block" of each slider works as planned as the conditional background-color, but the value is the same for all the sliders.

Here's my JS code:

$(document).ready(function() {
  $('.slider').slider({
    value: 5,
    min: 1,
    max: 10,
    step: 1,
    slide: function( event, ui ) {
      $( ".ui-slider-handle" ).text(ui.value);
      switch(ui.value){
        case 1: { $(this).css('background', 'darkred'); break;}
        case 2: { $(this).css('background', 'red'); break;}
        case 3: { $(this).css('background', 'orange'); break;}
        case 4: { $(this).css('background', 'gold'); break;}
        case 5: { $(this).css('background', 'yellow'); break;}
        case 6: { $(this).css('background', '#AAFF00'); break;}
        case 7: { $(this).css('background', 'lime'); break;}
        case 8: { $(this).css('background', 'cyan'); break;}
        case 9: { $(this).css('background', '#00AAFF'); break;}
        case 10: { $(this).css('background', 'blue'); break;}
      }
    }
  });
  $(".ui-slider-handle").val($('.slider').slider( "value" ));
});

And here's the code in JSfiddle: http://jsfiddle.net/Arkl1te/Wrq3H/

Is there a way to fix that? I appreciate your help!


回答1:


It's not that they have the same value, the problem is that you're updating both handles each time that a slide occurs. Possible fix: http://jsfiddle.net/Wrq3H/3/

//change text for current's slider handle only
        $(this).children(".ui-slider-handle").text(ui.value);



回答2:


You need to create a separate value parameter for each slider. They are referencing the same variable and therefore the step is being applied to both based on the latest value. Try something like:

valueone = 5,
valuetwo = 5,
/* ... other content ... */

$(".ui-slider-handle").val($('#slider-1').slider( "valueone" ));
$(".ui-slider-handle").val($('#slider-2').slider( "valuetwo" ));



回答3:


In function for slide you need to change your selector from all elements with ".ui-slider-handle" to children in element which raises slide event:

$(this).children( ".ui-slider-handle" ).text(ui.value);

That fix will allow you to use many sliders without changing function for slide Example http://jsfiddle.net/cVUp3/1/



来源:https://stackoverflow.com/questions/16680870/all-my-jquery-ui-single-sliders-get-the-same-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!