我正在尝试在页面上创建滑块的多个实例。每个滑块应该知道它当前正在查看哪个幻灯片。似乎当我更新slide
属性时,我为类更改它,而不是实例。这告诉我,我没有在我的公共init()
函数中正确实例化。我哪里错了?
var MySlider = (function() {
'use strict';
var animating = 0,
slides = 0, // total slides
slider = null,
slide = 0, // current slide
left = 0;
function slideNext(e) {
if ((slide === slides - 1) || animating) return;
var slider = e.target.parentNode.children[0],
x = parseFloat(slider.style.left);
animate(slider, "left", "px", x, x - 960, 800);
slide++;
}
return {
init: function() {
var sliders = document.querySelectorAll('.my-slider'),
l = sliders.length;
for (var i = 0; i < l; i++) {
sliders[i] = MySlider; // I don't think this is correct.
slider = sliders[i];
buildSlider(slider);
}
}
}
})();
答案 0 :(得分:4)
根据您的评论,我认为这更符合您的要求:
MySlider = (function () {
Slider = function (e) {
this.e = e;
// other per element/per slider specific stuff
}
...
var sliders; // define this out here so we know its local to the module not init
return {
init: function () {
sliders = document.querySelectorAll('.my-slider');
var l = sliders.length;
for (var i = 0; i < l; i++) {
sliders[i] = new Slider(sliders[i]); //except I'd use a different array
slider = sliders[i];
buildSlider(slider);
}
}
})();
这样,您将每个元素与其自己的元素特定数据相关联,但您有一个包含模块,您可以在其中操作您的模块集合。
答案 1 :(得分:3)
似乎当我更新slide属性时,我会为类更改它,而不是实例。
你是对的。该代码仅在定义MySlider类时运行。如果你想要一个实例变量,你需要在返回的对象中声明它,即返回块的一部分:
var MySlider = (function(param) {
return {
slider: param,
init: function() {
var sliders = document.querySelectorAll('.my-slider'),
l = sliders.length;
for (var i = 0; i < l; i++) {
sliders[i] = MySlider; // I don't think this is correct.
slider = sliders[i];
buildSlider(slider);
}
}
});