2015-05-04 41 views
0

我目前正在开发一个需要自定义滑块的项目,并且我迅速抓取了一个看起来整洁的Web教程,然后离开,并且静态地工作得很好。Javascript滑块功能 - 如何客观化选择器?

现在我想能够在我的页面上放几个滑块,因此需要动态地添加控件,而不是像下面所做的那样仅仅使用jQuery来选择某个滑块。

这是我与评论的代码加入到解释什么即时试图实现:

var Slider = function() { this.initialize.apply(this, arguments) }; 
Slider.prototype = { 

initialize: function(slider) { 
this.ul = slider.children[2]; 
this.li = this.ul.children; 
this.nav = slider.children[3]; //Why cant i use .append on this element? 

// make <ul> as large as all <li>’s 
this.ul.style.width = (100 * this.li.length) + '%'; 

// set width of the li's 
for(i = 0; i < this.li.length; i++) { 
    this.li[i].style.width = (100/this.li.length) + '%'; 
    $(".slider-nav").append('<div class="slider-dot"></div>'); //Want to make it a this.nav or something similar instead of an external selector 
    //console.log(this.nav); 
} 

this.currentIndex = 0; 
}, 

goTo: function(index) { 
if (index < 0 || index > this.li.length - 1) 
    return; 

// move <ul> left 
this.ul.style.left = '-' + (100 * index) + '%'; 

this.currentIndex = index 
}, 

goToPrev: function() { 
    this.goTo(this.currentIndex - 1) 
}, 

goToNext: function() { 
    this.goTo(this.currentIndex + 1) 
}} 

var sliders = []; 
$('.slider').each(function() { 
sliders.push(new Slider(this)); 
}); 

//Find a way to implement theese 2 within the slider function, how to find out what position in the array a slider has? 
$(".prev-btn").click(function() { 
sliders[0].goToPrev(); 
}); 

$(".next-btn").click(function() { 
sliders[0].goToNext();}); 

的痕迹了滑块看起来是这样的:http://puu.sh/hAUH1/a865792137.png

回答

0

我设法得到它通过定义这个工作作为另一个变种

var sliderEle = this; 

然后我可以这样称呼它:

$(this.prev).click(function(e) { 
    e.preventDefault(); 
    sliderEle.goToPrev(); 
}); 

与prev和next定义如下:

this.prev = slider.children[0]; 
this.next = slider.children[1];