jQuery sliders: only last slider working on page with multiple sliders

流过昼夜 提交于 2019-12-24 15:05:02

问题


I'm making a page with multiple sliders, where the number of sliders and the options are different based on the user. I'm having a problem where all of the sliders are created and shown, but only the last slider is draggable.

Simple jsfiddle to demonstrate what I'm talking about: http://jsfiddle.net/2crev/3/

I'm not sure what the issue is here. The ids for all the sliders are unique, and I'm creating the sliders after the html is there. Anyone know what's going on? Thanks! Getting issue on FF 26, Chrome 31, IE 11.


HTML:

<div id="sliders" style="width: 100px">
</div>

CSS:

div.slider {
    margin-top: 5px;
    margin-bottom: 30px;
}

JS:

var numberOfSliders = Math.floor(Math.random()*5) + 2;

for (var i=0; i < numberOfSliders; i++) {
    // Insert HTML
    var html = '<div>Slider '+i+'</div>'
              +'<div class="slider" id="slider-'+i+'"></div>';
    document.getElementById('sliders').innerHTML += html;

    // Create Slider
    $('#slider-'+i).slider({
        value: Math.floor(Math.random()*10) + 1,
        min: 0,
        max: Math.floor(Math.random()*5) + 10,
        step: 1,
        orientation: "horizontal",
        range: "min",
        animate: true
    });
}

console.log(document.getElementById('sliders').innerHTML);

回答1:


The problem is that you are replacing inner html in each loop iteration. In each loop iteration you:

  1. create 2 new divs,
  2. replace the <div id="sliders"> inner html
  3. and then initialize the jquery-ui slider on the new div.

The problem is in step 2. Because you are replacing inner html (you are replacing DOM elements), all events binded by jquery-ui are lost on the next loop iteration. Thus only, slider initialized on last iteration works.

Have a look in this jsFiddle in which jQuery .append() function is used instead of innerHTML :

$('#sliders').append(html);

With .append() you add only new elements to the DOM, not replacing all the existing one in the <div id="sliders">



来源:https://stackoverflow.com/questions/21062184/jquery-sliders-only-last-slider-working-on-page-with-multiple-sliders

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