如何使用jQuery.each()克隆和初始化jQuery Sliders

时间:2016-05-27 13:49:51

标签: javascript jquery html5 jquery-ui-slider

我正在尝试克隆jQuery范围滑块(最多5次)以保留相同的名称(作为数组发布)。

我设法让它工作,但第一个滑块是唯一可行的滑块。我尝试过使用$ this:

$(".slider").each(function () {

        $this = $(this);

        $("#slider-range", $this).slider({
                range: true,
                min: 18,
                max: 100,
                values: [ 21, 30 ],
                slide: function( event, ui ) {
                    $( "#amount" ).val(ui.values[ 0 ] + " - " + ui.values[ 1 ] );
                }
            });
            $( "#amount" ).val($( "#slider-range" ).slider( "values", 0 ) +
                " - " + $( "#slider-range" ).slider( "values", 1 ) );
        });

如果我在单击按钮后检查元素以克隆最后一个范围滑块我得到:

<div id="entry1" class="clonedInput">
<div class="slider">
<p>
    <label for="amount">Age range:</label>
    <input id="amount" readonly="" name="amount" style="border:0; color:#f6931f; font-weight:bold;" type="text">
</p>

<div class="ui-slider ui-slider-horizontal ui-widget ui-widget-content ui-corner-all" id="slider-range"><div style="left: 3.65854%; width: 10.9756%;" class="ui-slider-range ui-widget-header ui-corner-all"></div><span style="left: 3.65854%;" class="ui-slider-handle ui-state-default ui-corner-all" tabindex="0"></span><span style="left: 14.6341%;" class="ui-slider-handle ui-state-default ui-corner-all" tabindex="0"></span></div>
</div>

</div>

<div style="display: block;" id="entry2" class="clonedInput">
<div class="slider">
<p>
    <label for="amount">Age range:</label>
    <input id="amount" readonly="" name="amount" style="border:0; color:#f6931f; font-weight:bold;" type="text">
</p>

<div class="ui-slider ui-slider-horizontal ui-widget ui-widget-content ui-corner-all" id="slider-range"><div style="left: 3.65854%; width: 10.9756%;" class="ui-slider-range ui-widget-header ui-corner-all"></div><span style="left: 3.65854%;" class="ui-slider-handle ui-state-default ui-corner-all" tabindex="0"></span><span style="left: 14.6341%;" class="ui-slider-handle ui-state-default ui-corner-all" tabindex="0"></span></div>
</div>

</div>

1 个答案:

答案 0 :(得分:0)

1)在一个页面中使用一个DOM ID;
2)如果你想使用重复的类;
3)使用找到子元素的.find().children()

像这样:

var $this = $(this);
var amount = $this.find(".amount");
var slider = $this.find(".slider-range")
   .slider({
    range: true,
        min: 18,
        max: 100,
        values: [21, 30],
        slide: function (event, ui) {
            amount.val(ui.values[0] + " - " + ui.values[1]);
        }
    });

amount
    .val(slider.slider("values", 0) 
        + " - " 
        + slider.slider("values", 1));
});

example