jQuery滑块:只有最后一个滑块在具有多个滑块的页面上工作 [英] jQuery sliders: only last slider working on page with multiple sliders

查看:75
本文介绍了jQuery滑块:只有最后一个滑块在具有多个滑块的页面上工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个包含多个滑块的页面,其中滑块的数量和选项根据用户而有所不同.我在创建和显示所有滑块时遇到问题,但是只有最后一个滑块是可拖动的.

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.

简单的jsfiddle来演示我在说什么: http://jsfiddle.net/2crev /3/

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

我不确定这是什么问题.所有滑块的ID都是唯一的,在html出现之后,我将创建滑块.有人知道发生了什么吗?谢谢!在FF 26,Chrome 31,IE 11上出现问题.

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);

推荐答案

问题是您要在每次循环迭代中替换内部html. 在每个循环迭代中,您:

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

  1. 创建2个新的div,
  2. 替换 <div id="sliders"> 内部html
  3. 然后在新的div上初始化jquery-ui滑块.
  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.

问题出在步骤2中.由于要替换内部html(即要替换DOM元素),因此在下一次循环迭代中,所有由jquery-ui绑定的事件都将丢失.因此,只有在上一次迭代时初始化的滑块才起作用.

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.

看看 此jsFiddle ,其中jQuery .append() 函数代替了innerHTML:

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

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

使用.append(),您仅将新元素添加到DOM中,而不替换<div id="sliders">

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

这篇关于jQuery滑块:只有最后一个滑块在具有多个滑块的页面上工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆