问题
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:
- create 2 new divs,
- replace the
<div id="sliders">inner html - 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