jQuery UI - Slider - How to add values

十年热恋 提交于 2019-12-30 11:01:20

问题


fiddle - I've got set of values. Is it possible to add new handle or remove some of them without destroying and rebuilding slide instance?

Something like $('#slider').slider('addValueAt',5); or remove.

New value cannot be equal to any of actual, so there may be no more than 12 values.

Its custom code I've got alredy.

$(function () {
    var handlers = [0, 2, 4 , 9, 12];
    $("#slider").slider({
        min: 0,
        max: 12,
        values: handlers,
        slide: function (evt, ui) {
            for (var i = 0, l = ui.values.length; i < l; i++) {
                if (i !== l - 1 && ui.values[i] + 1 > ui.values[i + 1]) {
                    return false;
                }
                else if (i === 0 && ui.values[i] + 1 < ui.values[i - 1]) {
                    return false;
                }
            }
        }
    });
});

I've tried

$("#slider").slider('option','values', newArrayOfValues);

But it only moves actual values, not removing or adding new


回答1:


If you can upgrade to a version 1.10.x of jquery ui, you'd be able to do something like the following:

(function ($) {
    $.widget('my-namespace.customSlider', $.ui.slider, {
        addValue: function( val ) {
            //Add your code here for testing that the value is not in the list
            this.options.values.push(val);
            this._refresh();
        },
        removeValue: function( ) {
            this.options.values.pop( );
            this._refresh();
        }
    });
})(jQuery);

After that, you'd be able to use it like so:

$("#slider").customSlider({/* options */});

And add values:

$("#slider").customSlider('addValue', 5);

In this code, we're creating a new slider widget that inherits from the existing jquery-ui slider. In the addValue method, it's manually updating widget's internal array of values, and then calling the private _refresh() method of the original jQuery-ui slider, which is how the slider generates the handles in the first place when the widget is created. The _refresh() method was added in one of the more recent versions of jQuery ui. If you can't upgrade, this technique would still be possible, but you'd have to write code to inject the markup and bind the drag events.

Here's a fiddle showing this in action http://jsfiddle.net/ac2A3/5/

Your code to handle the slide event would have to change a little since it relies on the widget's values being in order.



来源:https://stackoverflow.com/questions/19348528/jquery-ui-slider-how-to-add-values

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