jQuery UI 控件之Slider

项目需要,页面上增加了2个slider控件用于设置range和limit,用的是jQuery UI官方的Slider:

jQuery UI 控件之Slider_第1张图片


但是我没有直接使用他的代码,因为我觉得写的不是很好,所以我自己写了一下,没想到出现了一些问题,就是在鼠标拖拽的过程中,数值更新不正常:

function updateDateRange(event, ui) {
    var slider = event.target;
    var values = $(slider).slider("values");
    this.find(".amount-date-range-start").val(values[0]);
    this.find(".amount-date-range-end").val(values[1]);
    this.find(".date-range-desc").text("from week " + values[0] + " to week " + values[1]);
}

function updateRecordCountLimit(event, ui) {
    var slider = event.target;
    var val = $(slider).slider("value");
    this.find(".amount-record-count-limit").val(val);
    this.find(".record-count-limit-desc").text(val);
}

function initPanel(panel, id) {
    $('a[href="#{id}"]'.replace('{id}', id)).click();
    panel.find(".slider-record-count-limit").slider({
        range: "max",
        min: 1,
        max: 500,
        value: 25,
        create: _.bind(updateRecordCountLimit, panel),
        slide: _.bind(updateRecordCountLimit, panel),
    });

    panel.find(".slider-date-range", panel).slider({
        range: true,
        min: 1,
        max: 60,
        values: [1, 25],
        create: _.bind(updateDateRange, panel),
        slide: _.bind(updateDateRange, panel),
    });

经过一番调试,发现是slide消息响应函数即updateXXX,不应该使用slider("value")来获取值,而是应该通过ui.value来获取,将代码改写,就OK了:

function updateDateRange(event, ui) {
    var slider = event.target;
    var values = (ui && ui.values) ? ui.values : $(slider).slider("values");
    this.find(".amount-date-range-start").val(values[0]);
    this.find(".amount-date-range-end").val(values[1]);
    this.find(".date-range-desc").text("from week " + values[0] + " to week " + values[1]);
}

function updateRecordCountLimit(event, ui) {
    var slider = event.target;
    var val = (ui && ui.value) ? ui.value : $(slider).slider("value");
    this.find(".amount-record-count-limit").val(val);
    this.find(".record-count-limit-desc").text(val);
}

function initPanel(panel, id) {
    $('a[href="#{id}"]'.replace('{id}', id)).click();
    panel.find(".slider-record-count-limit").slider({
        range: "max",
        min: 1,
        max: 500,
        value: 25,
        create: _.bind(updateRecordCountLimit, panel),
        slide: _.bind(updateRecordCountLimit, panel),
    });

    panel.find(".slider-date-range", panel).slider({
        range: true,
        min: 1,
        max: 60,
        values: [1, 25],
        create: _.bind(updateDateRange, panel),
        slide: _.bind(updateDateRange, panel),
    });


你可能感兴趣的:(jQuery UI 控件之Slider)